Paulund

VueJS - Vue Router Dynamic Routes

In a previous example we learnt how to use the Vue Router. In this example we just used simple links to a single page. But as you know most apps don't have simple links for the URLs and they're dynamic, for example in a blog the URL http://example.com/blog/{postname} the back-end will then search for the postname parameter in the database and show the content. This allows the website to only use one page for the unlimited number of urls. You can do the same thing in Vue Router by defining your routes with dynamic segments. For example in the blog post example you will need to define the route like the following.

const Blog = {
  template: '<div>Blog post page</div>'
}

const router = new VueRouter({
  routes: [
    { path: '/blog/:postname', component: Blog }
  ]
})

Now any URL that goes to /blog/random-post or /blog/this-post will be matched to the same route and will display the same blog post. This is because the dynamic segment of the URL is defined by the :postname, these route segments can be found in the this.$route object via the params property.

this.$route.params

This means we can now access this information inside the component by using this.$route.params.postname.

const Blog = {
  template: '<div>Blog post page - {{ $route.params.postname }}</div>'
}

Using the $route object you can also access other parameters such as - path - The full path of the route

  • params - Key/value of the dynamic segments
  • query - Key/value of query string parameters
  • hash - The route of the current hash value
  • matched - An array of matched routes
  • name - The name of the route