Reason: page refresh will cause vuex data loss, so routes cannot be added dynamically
1. Add the field isAddRoutes:false in the store user.js state to determine whether the addition of dynamic routes has been added. Function: Every time the page is refreshed, first judge whether the dynamic route is added, if not, add the dynamic route again.
2. After adding dynamic routes in mutations , assign true to the field isAddRoutes , indicating that dynamic routes have been added
//动态添加路由
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. Use the navigation guard in router index.js to operate the dynamic routing before the page jumps
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. GetInfo code in store user.js action:
// 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)
})
})
},
Enter the 404 page
Any routing redirection 404 page can be solved by adding it at the end.