Vue3 addRoute dynamic routing page refresh after the route fails [Vue Router warn]: No match found for location with path

Vue-router 4.0 cancels addRouters to set dynamic routing, only addRouter can be used

Dynamic routing is generally obtained from the backend and then processed by data format
insert image description here

But after the page is refreshed, the following warning will appear:

vue-router.esm-bundler.js?6c02:71 [Vue Router warn]: No match found for location with path “/formlist/stepform/other”

insert image description here

However, getRoutersall the asynchronous routing
analysis can be obtained through the pass : after the page is refreshed, it is obtained after the release of the next() function due to the asynchronous acquisition

At this time, it should be used next({ ...to, replace: true })to ensure addRoute()that the dynamically added routes have been fully loaded.

next({ ...to, replace: true })It is replace: truejust a setting information, telling VUE that after this operation, it cannot return to the previous route through the back button of the browser.

So next({ ...to, replace: true })it can be written next({ ...to }), but you should not want the user addRoute()to click the browser back button to do things before they are finished.

In fact next({ ...to }), the implementation is very simple, it will judge:

If the parameter to cannot find the corresponding route, execute it again beforeEach((to, from, next))until next({ ...to})the corresponding route can be found.

That is to say, it has been completed at this time addRoute(). After finding the corresponding route, the next step will be to go to the corresponding route beforeEach((to, from, next) . Therefore, you need to use code to judge whether this time is going to the corresponding route. beforeEach((to, from, next),If so, execute next() to let go.

If there is no correct release exit in the guard, it will always next({ ...to})enter an infinite loop!!!

So you also need to make sure that there is a correct direction exit in addRoute()the execution to this time when it has been done .beforeEach((to, from, next))next()

solve:

router.beforeEach(async (to, from, next) => {
    
    
    NProgress.start()
    to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${
      
      domTitle}-${
      
      to.meta.title}`))
    //判断是否登录
    if (VueCookies.get(ACCESS_TOKEN)) {
    
    
        if (to.path == '/loginview/login') {
    
    
            next({
    
     path: '/form/formlist' })
        } else {
    
    
        // 一定要有一个执行条件 否则会进入死循环
            if (store.state.permission.addRouters.length == 0) {
    
    
                await store.dispatch('GenerateRoutes').then((res) => {
    
    
                    const asyncRouter = res
                    asyncRouter.forEach(v => {
    
    
                        router.addRoute(v)
                    })
                    // 如果 addRoute 并未完成,路由守卫会一层一层的执行执行,直到 addRoute 完成,找到对应的路由
                    next({
    
     ...to, replace: true })
                })
            } else {
    
    
                next()
            }
        }

    } else {
    
    
        //免登录菜单
        if (whiteList.includes(to.name)) {
    
    
            next()
        } else {
    
    
            next({
    
     path: '/loginview/login', query: {
    
     redirect: to.fullPath } })
        }
    }
})

Add a 404 page to the basic routing of router.config.js (to prevent the warning prompt that the route is not found when the browser refreshes)

import {
    
     BasicLayouts, LoginView, RouteView } from '@/layouts'
/**
 * 基础路由
 * @type { *[] }
 */

export const routerMap = [
    {
    
    
        path: '/loginview',
        component: LoginView,
        redirect: '/loginview/login',
        children: [
            {
    
    
                path: '/loginview/login',
                name: 'login',
                component: () => import('@/views/Login/Login'),
                meta: {
    
     title: '登录' }
            },
        ]
    },
    {
    
    
        path: '/',
        component: BasicLayouts,
        redirect: '/home',
        children: [
            {
    
    
                path: '/home',
                name: 'Home',
                component: () => import('@/views/home/home'),
                meta: {
    
     title: '首页' }
            },
        ]
    },
    {
    
    
        hide: true,
        path: '/:pathMatch(.*)*',
        component: () => import('@/views/Exception/404'),
    },
   
]

The complete code address can refer to gtee: https://gitee.com/ZHANG_6666/crm-template/tree/develop/
Completely interact with the server: https://gitee.com/ZHANG_6666/crm-template
Server: https:/ /gitee.com/ZHANG_6666/express–vue3–ant-design2

Guess you like

Origin blog.csdn.net/weixin_43835425/article/details/116708448