问题出现的问题

  1. 动态路由添加刷新页面出现空白页面或者404页面

因为界面刷新导致动态路由丢失,所以是空页面或者404

  1. 我添加动态路由了怎么还剩刷新依旧是空白页面呢?

因为动态路由添加后需要是新导航才会生效

解决方案

需要判断当前页面是否刷新了

  1. 本地存一个当前访问页面的路由下次刷新用来判断当前是否是页面刷新
  2. 使用vuex来存储动态路由数据,如果是空就是刷新页面了

案例

  1. 使用本地存储 使用路由拦截器跳转之后存数据
//存访问路由
router.afterEach((to, from) => {
  localStorage.setItem("new",to.path)
  })
//处理动态路由
router.beforeEach((to, from, next) => {
 if(localStorage.getItem('new')){
        var path: any = localStorage.getItem('new')
        if (path == to.path) { //动态路由页面的刷新事件
          // localStorage.removeItem('new')
          store.commit('setBaseRouters')
          router.replace({...to});
        }
      }
})
  1. vuex处理更简单 需要添加路由拦截进行逻辑处理
router.beforeEach((to, from, next) => {
  store.commit('loginModule/isLogin')
  const isloginPage: boolean = getFilterRouterName((to.name as string));
  let state: any = store.state
  if (isloginPage || state.loginModule.isLogin) {
    if (state.baseRouters.length==0) {
      store.commit('setBaseRouters')
      router.replace({...to});
    }
    next()
  }
  else {
    next({ name: LOGIN })
  }
  if (to.matched.length === 0) {
    // ElMessage.warning("当前路由不存在");
    /**
     * user_type :customer
      user_type :  supplier
     */
      //只有登录了才进入这个逻辑判断
      if(state.loginModule.isLogin){
        if(localStorage.getItem('userinfo')){
                let data = JSON.parse(localStorage.getItem('userinfo'))
        if (data.user_type == 'customer') {
        //这里处理如果访问项目根路径访问的
          if (to.path == '/admin/') {
            router.replace(import.meta.env.VITE_BASE + "/***");
          }
        } else {
          next({ name: PRODUCT })
        }
        }
    
      }
    
  }
})
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐