Vue动态路由配置,f5刷新动态路由丢失等图文详解

Vue动态路由配置,f5刷新动态路由丢失,路由重定向报Promise的错误----------------其实超级简单

业务流程

用户登录(获取token)

得到用户token后,可以携带token(如果不需要token,请略过此步骤)请求动态路由接口

重点:动态路由数组存在本地

栗子:

// 用户登录
	PostUserToken(data)
      .then( response => {
    
    
        //设置token
        this.$cookie.set('access_token',response.data.access_token,response.data.expires_in+"S") 
        let data = {
    
     'access_token' : response.data.access_token }
        //获取动态路由数组
        GetMenuPath(data).then( response => {
    
    
          if(response.data.resp_code == 200){
    
    
            //动态路由存在本地-----退出登录时候清空
            localStorage.setItem('newRouterArr',JSON.stringify(this.returnRouterArr(response.data.data)));
          }else{
    
    
            this.$message.error('导航菜单获取失败,请联系管理员'); 
          }
          this.$message({
    
     message:'登录成功', type: 'success' });
          // 关闭loading
          this.loading = false;
        })
      })

设置动态路由(router/index.js),并且防止f5或者ctrl+r刷新丢失动态路由

重点:引入.vue文件得路径,num 等于 1 和等于 0的判断,最后的next()

baseUrl 是我的一个前缀,例如将前端代码部署包放在了 服务器:127.0.0.1:8080的 gateway 文件下,则baseUrl就等于 ‘/gateway’ ,你本地包跑起来,本地的地址也是 http://localhost:8080/gateway/

栗子 :


  // 获取动态路由
  let newRouterArr = JSON.parse(localStorage.getItem('newRouterArr'));
  //防止刷新时候(保证浏览器回退的时候)能直接返回到上个页面,不会叠加
  let num = 1;
  // 路由钩子
  router.beforeEach((to, from, next) => {
    
    

  //储存当前路由,便于在重新打开时候跳到上次关闭的页面(用户主动退出除外)
  if(to.name){
    
    
    localStorage.setItem('nowRouter',JSON.stringify(to));
  }else if(from.name){
    
    
    localStorage.setItem('nowRouter',JSON.stringify(from));
  }
  
  //首页时候,直接跳转(首页不是动态页面)
  if(to.path == baseUrl+"/" || to.path == baseUrl){
    
    
    next(baseUrl+'/index');
  }
  //不是首页,则添加动态路由(此时不确定用户去的是那个页面)
  else if(newRouterArr && num){
    
    
    num = 0;
    //配置动态路由 newRouterArr 中已经配置好了name和path,现在只需要指向组件对象
    newRouterArr.map((item,index)=>{
    
    
      //组件的储存位置是  src/view/business/组件名.vue
      newRouterArr[index].component = ()=>import('@/view/business/'+item.name+'.vue');
    })
    //添加路由
    router.addRoutes(newRouterArr);
    //跳转到相应页面
    router.replace(to.path);
  }
  else{
    
    
    next();
  }
  

解决Promise报错

有的小伙伴在这出现了Primise重定向的一个报错,那么我随便附上防止 Promise重定向报错 的一个方法

//解决Promise报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
    
    
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

千万不要相信网上某个小伙伴说的 升级vue-router ,那样只会导致你重新安装一次依赖

好的。到此,基本介绍完成了,
喜欢,就评论一下。
不喜欢,请说明原因。
感谢。

猜你喜欢

转载自blog.csdn.net/DoLi_JIN/article/details/106409270