动态路由参数怎么取不到?明明路径是对的啊
我用 Vue Router 做了个动态路由,比如 /user/:id,想在组件里拿到 id 参数。但 this.$route.params.id 一直是 undefined,控制台也报错说 Cannot read property ‘id’ of undefined。我已经确认路由配置没问题,页面也能正常跳转过去。
下面是我的路由配置和组件里取参数的代码:
const routes = [
{ path: '/user/:id', component: UserDetail }
]
// 在 UserDetail 组件中
export default {
mounted() {
console.log(this.$route.params.id) // 输出 undefined
}
}
mounted钩子里取this.$route.params.id,这时候可能路由还没完全解析好。试试在beforeRouteEnter守卫里取参数,或者换成created钩子,看行不行。代码改一下试试:或者这样:
这两种方法都能确保你在路由参数解析完之后再取值,应该能解决你的问题。希望这能帮到你,有时候这些小细节真是让人头大。
this.$route取不到说明 Vue Router 根本没挂载上。检查下 main.js 里有没有app.use(router)。另外确保组件是在
<router-view>里面渲染的,别直接当普通组件用。我一般直接在 mounted 里打印this.$route看看有没有东西,没有就是没注册上。