Accessing $route.params in VueJS

user8310317 picture user8310317 · Nov 21, 2017 · Viewed 39.9k times · Source

Looking through this documentation: https://router.vuejs.org/en/essentials/navigation.html

It looks like you can bind the <router-link :to="variableName">Link Text</routerlink> Which is pretty nifty; however, I've had some trouble trying to access route parameters inside of a component I'm trying to build.

So I use this:

<router-link :to="permalink">Title of thing</router-link>

To then direct the router view to pull the forum thread. Using this in the router:

import ForumThread from './views/groupTitle/forumThreadSingle';

// Other routes...
let routes = [
    {
        path: '/groupTitle/th/:id',
        component: ForumThread,
    } 
]; 

I can see in the forumthread component that $route.params.id is being passed too it; however, when I try to access it like this:

console.log('The id is: ' + $route.params.id);

It's unable to find the params portion of the object.

VueJS is pretty new to me as well as JavaScript itself. All the examples I've seen show the templates being inline with the router file which is something I am trying to prevent to help keep my code readable and clean.

What adjustments can I make so that I can pass properties to the template file?

Thanks!

Answer

Alex MacArthur picture Alex MacArthur · Nov 21, 2017

If you're using the Vue Loader setup (which has <template></template> tags in the files), you need to use this to reference the $router, if you're doing so within the <script></script> part of the file.

 console.log('The id is: ' + this.$route.params.id);