Handling Dynamic Routes with Vue Router

Matt Maribojoc
Level Up Coding
Published in
4 min readNov 11, 2019

--

Photo by Luke Chesser on Unsplash

Nobody will remember the url, http://yourwebsite.com/product/item-advxv12323-asdfa123 — so let’s convert it to something nicer.

While Vue Router is pretty straightforward, a problem that I’ve frequently found myself facing while building different applications is the idea of trying to make prettier paths for pages.

This article assumes you already know the basics of Vue Router. As long as you can set up your Vue project using the default Vue Router options (like in my ToDo App Tutorial *wink*), you’ll be at a great starting point.

This article will show you how to take the value in the URL path and pass it to your Vue component, allowing you to handle dynamic routes.

Overview

The example I’m going to be using is product pages. Essentially, all we have to do is utilize Vue Router’s ability to catch dynamic routes and pass it as a prop to a Vue component. Then, we can analyze the URL to determine if it matches an existing product. If it does, let’s show the product; otherwise, redirect to a 404 page.

Setting Up the Components

We will need to add two components:

  • A product page
  • A 404 page.

I’m not going to go into much depth on the design of the pages, we just need them to exist for the navigation purposes. Here are the example pages that I used.

Product.vue

<template lang="html">
<div>
Product Displayed: {{ product }}
</div>
</template>
<script>
export default {
props: ["product-path"],
data () {
return {
product: {}
}
},
created () {
// look up the product
// if it exists, proceed
}
}
</script>
<style lang="scss">
</style>

PageNotFound.vue

<template lang="html">
<div>
Error - Page Not Found
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss">
</style>

Configuring Vue-Router

--

--