Vue Router路径替换实现:如何避免路径拼接直接跳转至指定根路径?
解决Vue Router跳转路径自动拼接问题
看起来你在Vue Router的路由跳转上遇到了一个常见问题:点击Bar组件时,目标路径总是被追加到当前页面的路由后面,而不是直接跳转到你想要的绝对路径。别担心,这是因为你用了相对路径进行跳转,下面我给你两种简单可靠的解决方法:
问题根源
你当前的goTo方法里使用的path: \bar/${lang}/${id}`是相对路径,Vue Router默认会把这种路径拼接到当前激活的路由路径后面,所以在foo2页面点击时,就会变成foo2/bar/en/223344`。
解决方案
方案1:改用绝对路径跳转
如果你的目标是直接跳转到根路径下的/bar/:lang/:someId,需要做两步调整:
- 调整路由配置:把
bar路由从foo的子路由移到根级别,确保根路径能匹配到它:
routes = [ { path: '', name: 'home' }, { path: 'foo', component: () => import('@/views/Foo.vue') }, // 将bar路由移到根路由下 { path: 'bar/:lang/:someId', name: 'bar', component: () => import('@/views/Bar.vue') }, { path: 'foo2', component: () => import('@/views/Foo2.vue'), children: [ { path: 'bar2/:lang/:someId', name: 'bar2', component: () => import('@/views/Bar2.vue') } ] } ]
- 修改跳转方法:在路径开头加上
/,明确表示这是一个绝对路径:
methods: { goTo(lang, id) { // 前缀/表示从网站根路径开始跳转 this.$router.push({ path: `/bar/${lang}/${id}` }) } }
如果你的实际需求是跳转到foo下的子路由/foo/bar/:lang/:someId,那不需要调整路由配置,直接把路径写成/foo/bar/${lang}/${id}就行。
方案2:使用路由名称跳转(更推荐)
用路由的name来跳转是Vue Router的最佳实践之一,它会自动根据路由配置生成正确的绝对路径,完全不用操心相对/绝对路径的问题,而且后续修改路由路径时也不用改跳转代码:
- 确认路由配置的
name正确:你的现有配置里已经给bar路由加了name: 'bar',这很好,不用改:
routes = [ { path: '', name: 'home' }, { path: 'foo', component: () => import('@/views/Foo.vue'), children: [ { path: 'bar/:lang/:someId', name: 'bar', component: () => import('@/views/Bar.vue') } ] }, { path: 'foo2', component: () => import('@/views/Foo2.vue'), children: [ { path: 'bar2/:lang/:someId', name: 'bar2', component: () => import('@/views/Bar2.vue') } ] } ]
- 修改跳转方法,用
name和params传递参数:
methods: { goTo(lang, id) { this.$router.push({ name: 'bar', params: { lang: lang, someId: id } // 这里的key要和路由定义的参数名完全一致(someId) }) } }
额外需要修正的小问题
你的代码里路由组件的导入写法有语法错误,应该是component: () => import('@/views/Foo.vue'),而不是component: () => {'@/views/Foo.vue'},这个错误会导致组件无法正确加载,记得改过来哦!
内容的提问来源于stack exchange,提问作者Atousa Darabi
相关产品推荐
相关产品推荐

