VueJS | 如何访问我的Component中的Router Parameter

bon*_*low 11 vue.js vue-router vuejs2

我试图在我的Entry组件中访问我的参数:id.我用道具尝试了它,但它不起作用.任何的想法?找不到任何东西.

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

谢谢

Rus*_*ton 19

虽然soju的答案是正确的,但我倾向于使用docs称为"使用props解耦路由器"的方法.

这可以通过在您的路径中添加props:true选项并在组件中定义属性来实现.

所以在你的路线你会有:

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

然后在你的组件中添加一个道具:

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

这些都可以在文档中找到:将 道具传递给路径组件

  • 你应该接受这个答案而不是我的 (7认同)

soj*_*oju 16

你应该简单地使用这个:

__PRE__

阅读更多:https://router.vuejs.org/en/essentials/dynamic-matching.html

  • 网址已更改为https://router.vuejs.org/guide/essentials/dynamic-matching.html (2认同)

moh*_*ari 10

你可以在组件中使用

this.$route.params.id
Run Code Online (Sandbox Code Playgroud)

  • 请考虑在答案中添加更多信息 (4认同)

小智 6

在 html 中 <div>{{$route.params.id}}</div>

在脚本中 this.$route.params.id