Vue Router配置/tags/:id路由提示No match found报错如何解决?
问题根因
- 两个路由配置了重复的
name: 'Tags',Vue Router要求路由name全局唯一,重复标识会直接导致匹配逻辑混乱,这是你当前异常的核心原因。 - 若配置子路由,父路由对应组件内必须添加
<router-view>标签作为子路由的渲染出口,否则即使路由匹配成功,子组件也不会渲染。
实现方案
你的需求完全可以实现,以下提供两种符合要求的配置方式:
方案1:同级路由配置(保留/tags/:id路径格式)
仅需修改动态路由的唯一name即可,路由顺序无需调整:
// @/router/index.ts import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router' import Tags from '@/views/Tags/index.vue' import SingleTag from '@/views/Tags/Single.vue' const routes: Array<RouteRecordRaw> = [ { path: '/tags', name: 'Tags', component: Tags, }, { path: '/tags/:id', name: 'SingleTag', // 改为全局唯一的路由名称 component: SingleTag, }, ] const router = createRouter({ history: createWebHashHistory(), routes, }) export default router
方案2:子路由层级配置(同时满足路径格式+子路由层级要求)
步骤1:调整路由配置
// @/router/index.ts import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router' import Tags from '@/views/Tags/index.vue' import SingleTag from '@/views/Tags/Single.vue' const routes: Array<RouteRecordRaw> = [ { path: '/tags', name: 'Tags', component: Tags, children: [ { path: ':id', // 子路由path不加前缀/,会自动拼接父路由路径,最终匹配规则为/tags/:id name: 'SingleTag', component: SingleTag, } ] }, ] const router = createRouter({ history: createWebHashHistory(), routes, }) export default router
步骤2:添加渲染出口
在@/views/Tags/index.vue文件的合适位置添加<router-view />标签,用来渲染子路由的SingleTag组件。
如果需要标签列表页和编辑页完全独立、不共用列表页布局,可以将父路由改为空布局组件(仅包含<router-view />),再将列表页设为默认子路由:
const routes: Array<RouteRecordRaw> = [ { path: '/tags', component: () => import('@/layout/Empty.vue'), // 空布局组件内部仅写<router-view /> children: [ { path: '', name: 'Tags', component: Tags, // 原标签列表页作为默认子路由 }, { path: ':id', name: 'SingleTag', component: SingleTag, } ] }, ]
内容的提问来源于stack exchange,提问作者Spedwards
相关产品推荐
相关产品推荐

