Problem description

Yesterday, when I was doing the function of dynamically adding the permission page to the route in the VUE background management system, I encountered a problem: 404 appeared when the page was refreshed for the dynamically added route page.

scenario

The permission control of the background management system is to define the permission code on the front page, save the code configuration to the background students in the table, and then filter and match according to the permission code list returned by the background and the code menu list configured on the front page. The page with the same code is the page with permission. Then add the route to the router using router.addroute (). Only the authorized route can be accessed. Otherwise, a message is displayed indicating no permission.

Fixed routes are initially placed in the new Router, such as the login page

Interface to return

Front menu definition

Method in VUex

Problems that arise

After login, obtain the permission code and dynamically filter the permission route page by invoking the vuEX method. Then, add the permission menu to the route using router-addroute () to access the dynamically added route page, refresh the page, and 404 is displayed

Cause analysis,

When the page is refreshed, routes are re-initialized. The dynamically added routes no longer exist, and only some fixed routes (such as the login page) still exist. Therefore, 404 occurs

The solution

Data stored in the VUEX Store is cleared when the page is refreshed. Make a judgment in the global navigation router-beforeeach of routes, and judge whether the page is refreshed according to whether the list stored in VUEX has value. If it is not 0, it is the first login. After login, the route will be matched, and there is no problem. If list.length is 0, the page is refreshed, routes need to be matched again, and dynamic routes need to be added again.

Add logic to the navigation guard of route/index.js

———router.js————-

const constantRoutes = [
    {
        path: '/'.redirect: '/login'
    },
    {
        path: '/login'.name: 'login'.meta: {
            auth: false
        },
        component: () = > import('@/views/login')}, {path: '/layout'.name: 'layout'.meta: {
            auth: true
        },
        component: () = > import('@/views/layout/index'),
        children: [{path: '/index'.name: 'index'.component: () = > import('@/views/home')}]}, {path: The '*'.component: () = > import('@/views/error/404')
    }
]

Vue.use(VueRouter)
const createRouter = () = >
    new VueRouter({
        routes: constantRoutes
    })
export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // reset router
}
const router = createRouter()
 
// After the page is refreshed, reset the dynamic route of the permission page to prevent dynamic route 404 problem
const reSetPermissionList = to= > {
    return new Promise((resolve, reject) = > {
        if(to.path ! = ='/login' && store.state.permission.permissionList.length === 0) {
            store
                .dispatch('permission/getPermissionList')
                .then(() = > {
                    resolve('permCode')
                })
                .catch(error= > {
                    resolve('permCode')})}else {
            resolve()
        }
    })
}
router.beforeEach((to, from, next) = > {
     
    const accessToken = localStorage.getItem('accessToken')
    if (_.isEmpty(accessToken)) {// Have you logged in? No Go to the login page
        next({
            path: '/login'.query: {
                redirect: to.fullPath
            }
        })
    } else { // The login page is displayed
        if (to.path === '/login') {
            next({ path: '/index'})}else {
             reSetPermissionList(to).then(data= > {
                    data === 'permCode' ? next({ path: to.path, query: to.query }) : next()
                })
        }
    }
   
})
Copy the code

conclusion

It mainly determines whether the data in VUEX exists in the global navigation, and determines whether the page is refreshed. If yes, it is a way to re-match the permission route.

Ending Egg

The first time encountered this problem, more meng lack…… ^3^ {% link Refer to the article link – go to blog.csdn.net/qq_31906983… %}

Postscript for March 2021

There is a problem: global navigation using routing routers. BeforeEach interception determines whether the data in VUEX exists, which is good as a basis for whether the page is refreshed, but…. If the backend interface returns an empty array of permissions, the request for this permission will loop….

It is not possible to have no permissions at all, at least give the default permissions, but we have no permissions to return empty. If the list is null, there will be a logical conflict, so I will add a value to the list, as long as the value does not correspond to the routing menu of the front desk, and the user will not be aware of the existence of this permission.

Having said all that, let’s look at the code:

    const actions = {
    // Obtain permission data
    async getPermissionList({ commit, state }, args = 'geting') {
        console.log('Get permission', state)
        return new Promise(async (resolve, reject) => {
            resetRouter()             
            const [res] = await myPermissionCodes({ clientId, orgCode: storage.get('orgCode') | |' ' })
            if (res) {
                / / changes here > > > > > > > > = = = = = = = = = = = = = = = ^ - ^ = = = = = = = = = = = = = = = = =
                letlist = res.list.length ! = =0 ? res.list : ['testCode']// Return an empty array with a value in front
                commit('updatePermissionList', list)
                resolve(list)
            } else {
                // Automatically log out...
                storage.clear()
                router.replace('/login')
                reject()
            }
        })
    }
}
Copy the code

This article was first published on my personal blog. Welcome to xi Xi