Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS | How to get access to Router Parameter in my Component

I tried to get access to my parameter :id in my Entry component. I tried it with props but it doesn't work. Any idea? Can't find anything.

export default new Router({
    routes: [{
        path: '/entry/:id',
        name: 'Entry',
        component: Entry
    }]
})

Thank you

like image 580
bonblow Avatar asked Jan 25 '18 15:01

bonblow


People also ask

How do I access my router props?

Another way to access the router props is to add an import statement at the top of the component and import 'withRouter'. import { withRouter } from 'react-router-dom'; Then in the export default statement at the end of the component you would wrap the component in 'withRouter'. export default withRouter(HomePage);


2 Answers

While soju's answer is correct, I tend to use the method in which the docs refer to as 'decoupling the router using props'.

This can be accomplished by add the props: true option to your route and defining a property in your component.

So in your Route you would have:

export default new Router({
     routes: [{
          path: '/entry/:id',
          name: 'Entry',
          component: Entry,
          props: true
     }]
})

Then in your component you add a prop:

Vue.component('Entry', {
       template: '<div>ID: {{ id}}</div>',
       props:['id']
})

This can all be found in the docs: Passing Props to Route Components

like image 61
Russell Shingleton Avatar answered Oct 18 '22 22:10

Russell Shingleton


You should simply use $route.params.id or this.$route.params.id.

Read more : https://router.vuejs.org/guide/essentials/dynamic-matching.html

You should consider using props : https://router.vuejs.org/en/essentials/passing-props.html

like image 23
soju Avatar answered Oct 19 '22 00:10

soju