Exit processing of vue-router

1. There is no official deletion method for vue-router3 (vue2)

Strategy: Create a new router object and assign the matcher to the old one

const router1=new Vue ({...})  

const router2=new Vue ({...})  

router1.matcher = router2.matcher

const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

2. vuew-router4 (vue3) provides

The removeRoute method deletes the registered route,
export function resetRouter(){
    let routers = router.getRoutes()
    routers.map(it=>{
        if(!['login','404','notFind'].includes(it.name)){
            router.removeRoute(it.name)
        }
    })
}

3. The overall plan:

Delete the token, jump to the login page, and clear the registered route at the same time (to prevent the access to another role after switching roles), add token detection in beforeEach

Guess you like

Origin blog.csdn.net/qq_34907249/article/details/128381555