控制台警告:Duplicate named routes definition { name Config, path visitiorconfig

控制台警告:Duplicate named routes definition: { name: "Config", path: "/visitior/config"}

image-20230711101558020

警告产生的原因

根据提示内容,猜测是和路由的name有关。警告是由于路由的name 重复导致的。

错误类型

一是静态路由中的name重复,一是动态路由的name 重复

静态路由:
错误dome:
{
    path: '/storage-pool',
    name: 'storagePool',   // name 1
    component: Layout,
    children: [
      {
        path: 'drag-table',
        name: 'DragTable', // name 2
        meta: { title:'' },
        component: () => import('@/views/storage-pool/storage-pool/index')
      }
    ]
  },
{
    path: '/pool',
    name: 'storagePool', // name 3
    component: Layout,
    children: [
      {
        path: 'drag-table',
        name: 'DragTable2', // name 4
        meta: { title: ''},
        component: () => import('@/views/storage-pool/storage-pool/index')
      }
    ]
  },

以上demo 包括子路由一共有4个name值,其中name1 和name3 是重复的。这样就会产生Duplicate named routes definition 的警告了。

解决方式:

静态路由的解决方式很简单,只要调整一下name,使所有name 不重复即可.4个路由name重新命名。

动态路由:

这里重点要说的是动态路由。动态路由一般来说是通过后端接口返回拿到数据,然后在路由守卫router.beforeEach 中进行添加。

错误Demo:
 router.beforeEach(async(to, from, next) => {
  if (to.name === 'storageNew') {
    getAside().then(res => {
      router.options.routes = res 
      router.addRoutes(router.options.routes)
      next()
    })
  } else {
    next()
  }
})

以上demo 运行也会出现警告 Duplicate named routes definition,这里的重点是方法 addRoutes,因为: addRoutes 方法仅仅是帮你注入新的路由,并没有帮你剔除其它路由。

解决方案:

这里我们使用addRoutes之前,将新的路由记录传递给matcher。即:router.matcher = new Router().matcher;放在一起就是

router.options.routes = res
router.matcher = new Router().matcher //match
router.addRoutes(router.options.routes)

页面初始化的警告消失了,在点击动态路由的时候会发现,还是会出现警告。检查一下代码发现,我们每次页面跳转的时候,在router.beforeEach 里都会请求一次地址getAside ,重新使用方法addRoutes。

那么让请求只执行一次,会不会就解决问题了尼?

这里我使用了localStorage,页面初始化设置localStorage 为0,在第一次请求拿到动态地址之后存储一下状态为1,之后由于是单页面不会刷新页面,那么只要在beforeEach添加判断就可以了。

完整代码:

window.localStorage.setItem('storageAside', '0')
router.beforeEach(async(to, from, next) => {
  if (to.name === 'storageNew' && window.localStorage.getItem('storageAside') === '0') {
    getAside().then(res => {
      window.localStorage.setItem('storageAside', '1')
      router.options.routes = res
      router.matcher = new Router().matcher
      router.addRoutes(router.options.routes)
      next()
    })
  } else {
    next()
  }
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值