Vue 2中如何在路由定义内访问路由参数?
解决Vue 2路由beforeEnter中获取路由参数的问题
- 你的代码里直接使用
district_id会触发未定义错误,路由参数需要从beforeEnter钩子的第一个参数to的params属性中获取。 - 修正后的路由配置代码如下:
{ path : '/dashboard/:district_id/', redirect : '/dashboard/:district_id/home', name : 'DashboardHome', component: DashboardContainer, meta : { label : 'Dashboard', requiresAuth: true, }, beforeEnter: (to, from, next) => { // 从to.params中提取路由参数district_id const districtId = to.params.district_id; const hasAccess = store.state.currentUser.districts.includes(districtId); if (hasAccess) { next() } else { next('/403'); } }, }
- 关键注意点:
to.params存储了当前路由匹配到的所有动态参数,参数名要和路由path中:后面的定义完全一致(包括大小写)- 如果参数是数字类型,可能需要额外做类型转换(比如
Number(to.params.district_id)),避免字符串匹配失败
内容的提问来源于stack exchange,提问作者brandkast
相关产品推荐
相关产品推荐

