浏览器 |如何访问我的组件中的路由器参数
VueJS | How to get access to Router Parameter in my Component
我试图在我的 Entry 组件中访问我的参数 :id。我用道具试了一下,但没用。任何的想法?找不到任何东西。
export default new Router({
routes: [{
path: '/entry/:id',
name: 'Entry',
component: Entry
}]
})
谢谢
您应该只使用 $route.params.id
或 this.$route.params.id
。
阅读更多:https://router.vuejs.org/guide/essentials/dynamic-matching.html
你应该考虑使用道具:https://router.vuejs.org/en/essentials/passing-props.html
虽然 soju 的回答是正确的,但我倾向于使用文档中提到的方法 'decoupling the router using props'。
这可以通过将 props: true 选项添加到你的路由并在你的组件中定义一个 属性 来实现。
因此在您的路线中您将拥有:
export default new Router({
routes: [{
path: '/entry/:id',
name: 'Entry',
component: Entry,
props: true
}]
})
然后在你的组件中添加一个道具:
Vue.component('Entry', {
template: '<div>ID: {{ id}}</div>',
props:['id']
})
这些都可以在文档中找到:
Passing Props to Route Components
你可以在组件中使用
this.$route.params.id
同在html<div>{{$route.params.id}}</div>
在脚本中 this.$route.params.id
<template>
<div>
<p>{{id}}</p>
</div>
</template>
<script>
export default {
data() {
return {
id:this.$route.params.id
}
},
}
</script>
我试图在我的 Entry 组件中访问我的参数 :id。我用道具试了一下,但没用。任何的想法?找不到任何东西。
export default new Router({
routes: [{
path: '/entry/:id',
name: 'Entry',
component: Entry
}]
})
谢谢
您应该只使用 $route.params.id
或 this.$route.params.id
。
阅读更多:https://router.vuejs.org/guide/essentials/dynamic-matching.html
你应该考虑使用道具:https://router.vuejs.org/en/essentials/passing-props.html
虽然 soju 的回答是正确的,但我倾向于使用文档中提到的方法 'decoupling the router using props'。
这可以通过将 props: true 选项添加到你的路由并在你的组件中定义一个 属性 来实现。
因此在您的路线中您将拥有:
export default new Router({
routes: [{
path: '/entry/:id',
name: 'Entry',
component: Entry,
props: true
}]
})
然后在你的组件中添加一个道具:
Vue.component('Entry', {
template: '<div>ID: {{ id}}</div>',
props:['id']
})
这些都可以在文档中找到: Passing Props to Route Components
你可以在组件中使用
this.$route.params.id
同在html<div>{{$route.params.id}}</div>
在脚本中 this.$route.params.id
<template>
<div>
<p>{{id}}</p>
</div>
</template>
<script>
export default {
data() {
return {
id:this.$route.params.id
}
},
}
</script>