Vue Router跳转后beforeRouteEnter获取的from路由不符合预期求助
问题原因
核心原因是跳转时将hash参数直接拼接在path路径中,加上路由配置开启了strict严格匹配,导致路由无法命中定义的/feature规则,出现隐式重定向/404匹配,因此from路由信息不符合预期。
Vue Router的path字段仅识别路径部分,hash、query等参数需要单独配置,直接拼接在path中会被当作路径的一部分参与匹配,strict: true配置会进一步严格匹配规则,完全无法识别路径后携带的hash内容,最终导致路由匹配失败。
修复方案
方案1:修正路由跳转写法(无需修改路由配置)
把所有跳转代码的hash单独抽离配置即可:
- 编程式跳转修正:
createNewFeature() { this.$router.push({ path: '/feature', hash: '#new' }) }
- router-link写法修正:
<router-link :to="{ path: '/feature', hash: '#new' }">go</router-link>
修改后跳转即可正确命中/feature路由,from字段会正常显示来源的产品页路由。
方案2:子路由配置(如需通过路径区分新建/编辑等状态)
如果你想要用路径而非hash区分功能状态,可以配置子路由,示例配置如下:
{ path: '/feature', name: 'CustomFeature', component: CustomFeature, pathToRegexpOptions: { strict: true }, meta: { title: 'Custom features', scrollToTop: true, }, children: [ { path: 'new', name: 'NewFeature', // 若要复用父组件可省略component配置,或填入对应新建功能的组件 meta: { title: '新建自定义功能', scrollToTop: true } } ] }
跳转时对应写法:
this.$router.push('/feature/new') // 或基于name跳转,更便于后续维护 this.$router.push({ name: 'NewFeature' })
内容的提问来源于stack exchange,提问作者camelyellow
相关产品推荐
相关产品推荐

