Vue.js 3动态URL路由与404页面异常问题求助
问题修复方案
针对你遇到的两个路由配置问题,以下是具体修复步骤和修正后的代码:
问题1:无效URL跳转404后URL被修改
原代码存在变量错误,且跳转404的方式会触发路由导航导致URL变更。修复要点:
- 修正变量名错误:将
const item = to.params.lang;改为const product = to.params.product;,确保正确获取路由参数 - 修改404跳转逻辑:通过传递原路径的参数、查询信息,实现渲染NotFound组件的同时保留原URL
问题2:带尾斜杠的无效URL显示空白
原路由顺序和匹配逻辑未覆盖带尾斜杠的无效路径。修复要点:
- 将404路由放在路由数组最后一位,确保所有未匹配的路径(包括带尾斜杠的)都能被捕获
- 利用Vue Router默认的
strict: false配置,自动忽略尾斜杠,让合法路径的带尾斜杠形式也能正常匹配动态路由
修正后的完整代码
var productArray = [ { label: "product1", code: "p1", }, { label: "product2", code: "p2", }, { label: "product3", code: "p3", } ]; const routes = [ { path: "/:product", component: Home, beforeEnter(to, from, next) { // 正确获取路由参数 const product = to.params.product; // 检查产品是否合法 const isValidProduct = productArray.some(e => e.code === product); if (!isValidProduct) { // 跳转404并保留原URL的所有信息 next({ name: "notFound", params: { pathMatch: to.path.slice(1).split('/') }, query: to.query, hash: to.hash, replace: true }); } else { next(); } }, }, { path: "/", redirect: 'p1', }, // 404路由必须放在最后,确保所有未匹配路径被捕获 { path: "/:pathMatch(.*)*", name: "notFound", component: NotFound, }, ]; const router = createRouter({ history: createWebHistory(), routes, }); let app = createApp(App); app.use(router); app.mount("#app");
额外说明
replace: true避免在浏览器历史记录中添加多余的导航记录productArray.some()比find()更适合做存在性检查,性能更优/:pathMatch(.*)*语法会捕获所有层级的路径,包括带尾斜杠的无效路径
内容的提问来源于stack exchange,提问作者Kango
相关产品推荐
相关产品推荐

