vue动态路由添加后刷新显示空白页或404

2022-08-08 12:45:26

刷新显示空白页面

原因:页面刷新会导致vuex数据丢失,所以无法动态添加路由

1、在store user.js state中添加字段isAddRoutes:false,用来判断是否已经添加完动态路由的添加。作用:每次页面刷新时都先判断一下动态路由是否添加,若没有,重新添加动态路由。

2、在mutations中完成动态路由添加后,给字段isAddRoutes赋值为true,表明已添加动态路由

//动态添加路由

 SET_RESULTASYNCROUTES(state, resultAsyncRoutes) {

    state.resultAsyncRoutes = resultAsyncRoutes

// anyRoutes 为重定向404路由,必须放在最后添加,防止登录或刷新显示404

state.allRoutes = constantRoutes.concat(state.resultAsyncRoutes, anyRoutes)

    router.matcher = new Router({ mode: 'history' }).matcher;

    router.addRoutes(state.allRoutes)

state.isAddRoutes = true

  }

3、在router index.js中利用导航守卫,在页面跳转前对动态路由进行操作

const router = createRouter()

router.beforeEach(async (to, from, next) => {

// 获取token,没有获取退出和重新登录会报错

  let token = getToken()

  if (token) {

        //当用户有登录,不能显示登录页面,直接进首页

    if (to.path === 'login') {

      next({ path: '/' })

    }

        //当字段isAddRoutes为false,重新dispatch getInfo,达到重新添加动态路由

    if (!store.state.user.isAddRoutes) {

      await store.dispatch('user/getInfo')

      next({

        ...to,

        replace: true

      })

    } else {

      next()

    }

  } else {

    if (to.path !== '/login') {

      next({ path: '/login' })

    } else {

      next()

    }

  }

})

4、store user.js action中getInfo代码:

  // get user info

  getInfo({ commit, state }) {

    // console.log('getInfo');

    return new Promise((resolve, reject) => {

      getInfo(state.token).then(response => {

        const { data } = response

        commit('SET_USERINFO', data)

       // comparisonRoutes封装函数 服务器中的路由数据和默认异步数据的对比,提取正确一部路由

  commit('SET_RESULTASYNCROUTES', comparisonRoutes(cloneDeep(asyncRoutes), data.routes))

        if (!data) {

          return reject('Verification failed, please Login again.')

        }

        resolve(data)

      }).catch(error => {

        reject(error)

      })

    })

  },

进入404页面

任意路由重定向404页面放在最后添加即可解决。

  • 作者:nniicchheerr
  • 原文链接:https://blog.csdn.net/nniicchheerr/article/details/124663945
    更新时间:2022-08-08 12:45:26