Vue动态路由路径重复及刷新丢失页面问题的解决

Vue动态路由路径重复及刷新丢失页面

1.使用router.addRoutes(teacherRouter);

添加完路由切换路由时,vue会警告路由名字重复

问题出现原因是:动态路由添加时调佣addRoutes();它只会帮你注入路由,不会帮你把前面的路由清掉。如此一来就重复添加了。

解决方法:路由动态添加关键页面需要在路由配置页(router/index.js)添加自定义方法

router.$addRoutes = params => {
  router.matcher = new Router({
    routes: router.options.routes
  // 关键代码
  }).matcher;
  router.addRoutes(params);
};

2.问题

在添加后进行页面刷新后,动态添加的路由会消失,路劲找不到

可以使用localstorage缓存,页面路由权限判断页(promission.js)用了路由beforeEach可以直接判断路由刷新:

if (from.name === null) {
      // 刷新
      router.$addRoutes(accessRoutes);
      // 确保页面加载完成
      next({ ...to, replace: true });
  } 

3.问题

切换不同角色权限,之前动态添加的路由没有被清除,进入看到的还是上次进入的权限页面。

问题在于vue的store没有被清空,把store里的route清空就行:

可以在退出登录设置,也可以在添加路由时清空,以下代码为store内permission.js添加动态路由前清空路由

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
  RESET_ROUTES: (state, payLoad) => {
    state.addRoutes = [];
    state.routes = [];
  }
}; 
generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // 关键代码 == 添加路由前将路由重置为空
      commit("RESET_ROUTES");
      // 设置登录的路由权限
      let accessedRoutes;
   
     if (roles === 4) {
        // 教师登录
       accessedRoutes = teacherRouter;
     }
     if (roles === 3) {
       // 学生登录
       accessedRoutes = studentRouter;
     }

     commit("SET_ROUTES", accessedRoutes);
     resolve(accessedRoutes);
   }); 

Vue路由动态添加重复警告重复

动态添加路由后,控制台警告重复,在router.js中添加下面代码

const createRouter = () => new Router({
     mode: 'history',
     routes: constantRoutes
})
const router = createRouter()
export function resetRouter () {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher
}
export default router

addRoutes()方法是router自带的原生方法,是动态添加路由的,它并没有删除之前路由中原有的路由所以在permission.js中引入router,并且添加在addRoutes之前resetRouter

import router,{resetRouter} from './router'
store.dispatch('GenerateRoutes').then(accessRoutes => {
    // 根据roles权限生成可访问的路由表
    resetRouter()
    router.addRoutes(accessRoutes)// 动态添加可访问路由表
})

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/wy17324808055/article/details/121606475