通常在组件中使用路由参数,大多数人会做以下事情。
export default {
methods: {
getParamsId() {
return this.$route.params.id
}
}
}
在组件中使用 $route 会导致与其相应路由的高度耦合,通过将其限制为某些 URL 来限制组件的灵活性。正确的做法是通过 props 来解耦。
const router = new VueRouter({
routes: [{
path: /user/:id ,
component: User,
props: true
}]
})
将路由的 props 属性设置为 true 后,组件内部可以通过 props 接收 params 参数。
export default {
props: [ id ],
methods: {
getParamsId() {
return this.id
}
}
}
您还可以通过功能模式返回道具。
const router = new VueRouter({
routes: [{
path: /user/:id ,
component: User,
props: (route) => ({
id: route.query.id
})
}]
})