动态添加路由

动态添加路由遇到的问题

1,添加方法:

  // temp 里是动态的路由表

  router.options.routes = router.options.routes.concat(temp)
  
   // $addRoutes是自己实现的方法
  router.$addRoutes(router.options.routes)
  
  
   // 具体原因:在做路径切换transitionTo方法中,首先就会使用const route = this.router.match(location, this.current)来匹配route, 其实内部会使用matcher来做匹配。修改了matcher即新的routes生效。 
  router.$addRoutes = (params) => {
    router.matcher = new Router({mode: 'history'}).matcher;
    router.addRoutes(params)
  }
2,添加时机:
  
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (to.path != '/login' && to.path != '/regist') {
    if(user){
      addTree()  // 添加一次
      setTimeout(next(),100)
    }else{
      next({ path: '/login' })
    }
  } else {
    next()
  }
})
 
3,刷新失效问题:
在App.vue 中添加钩子 created 这样每次刷新都会执行
在钩子中重新添加路由

猜你喜欢

转载自www.cnblogs.com/maoye618/p/12566010.html