首页 > 其他分享 >【vue-router 4.x】使用addRoute加载动态路由时,刷新页面后出现空白页和控制台报错 [Vue Router warn]: No match found for location wi

【vue-router 4.x】使用addRoute加载动态路由时,刷新页面后出现空白页和控制台报错 [Vue Router warn]: No match found for location wi

时间:2022-12-04 16:25:11浏览次数:39  
标签:No URL next item 报错 path router 路由

"vue-router": "^4.1.6" 遇到的问题

  1. 动态路由刷新后,出现空白页
  2. 动态路由刷新后,控制报错[Vue Router warn]: No match found for location with path "/***/index"

1.动态路由,刷新后出现空白页如何解决

通过打断点可知,刷新后进入页面,to.matched为空数组,即此时next跳转则会出现空白页面。
使用next({ ...to, replace: true })来确保addRoute()时动态添加的路由已经被完全加载上去。

next({ ...to}) 能保证找不到路由的时候重新执行beforeEach钩子

next({ replace: true}) 保证刷新时不允许用户后退

路由拦截器

router.beforeEach(async (to, from, next) => {
    // 1.NProgress 开始
    NProgress.start()

    // 2.路由跳转之前,清除所有的请求
    axiosCanceler.removeAllPending()

    // 3.判断是访问登录页,直接方向
    if (to.path === LOGIN_URL) return next()

    // 4.判断是否有token,没有重定向到登录页面
    const globalStore = GlobalStore()
    if (!globalStore.token) return next({ path: LOGIN_URL, replace: true })

    // 5.如果没有菜单列表,就重新请求菜单列表并添加动态路由( next({ ...to, }) 会不停调用beforeEach直到找到to.matched)
    const authStore = AuthStore()
    if (!authStore.authMenuListGet.length) {
        await initDynamicRouter()
        return next({ ...to, replace: true })
    }
    // 6.放行页面
    next()
})

添加动态路由的方法(仅参考)

export const initDynamicRouter = async () => {
    try {
        // 1.获取菜单列表 && 按钮权限
        const authStore = AuthStore()
        await authStore.getAuthButtonList()
        await authStore.getAuthMenuList()

        // 2.判断当前用户有没有菜单权限
        if (!authStore.authMenuListGet.length) {
            ElNotification({
                title: "无权访问",
                message: "当前账号无任何菜单权限,请联系系统管理员!",
                type: "warning",
                duration: 3000
            })
            router.replace(LOGIN_URL)
            return Promise.reject("No permission")
        }

        // 3.添加动态路由(通过getFlatArr 方法把菜单全部处理成一维数组,方便添加动态路由
        let dynamicRouter = getFlatArr(JSON.parse(JSON.stringify(authStore.authMenuList)))
        dynamicRouter.forEach((item: any) => {
            if (item.children) delete item.children
            if (item.component) item.component = modules["/src/views" + item.component + ".vue"]
			// 判断是否为全屏路由
			if (item.meta.isFull) {
				router.addRoute(item);
			} else {
				// 添加到父路由layout下面添加新的路由
				router.addRoute("layout", item);
			}
        })

    } catch (error) {
        // 当按钮和菜单 请求出错时,重定向到登录页
        router.replace(LOGIN_URL)
        return Promise.reject(error)
    }
}

2.刷新后控制台报错如何解决

添加一个静态路由,匹配任意路径指向404错误页面。这样能保证控制不会报错[Vue Router warn]: No match found for location with path "/***/index"

export const staticRouter: RouteRecordRaw[] = [
    {
        path: "/",
        redirect: LOGIN_URL
    },
    {
        path: LOGIN_URL,
        name: "login",
        component: () => import("@/views/login/index.vue"),
        meta: {
            title: "登录页"
        }
    },
    // 主页框架
    {
        path: "/layout",
        name: "layout",
        component: () => import("@/layouts/LayoutVertical/index.vue"),
        redirect: HOME_URL,
        children: []
    },
    {
        // hide: true,
        path: '/:pathMatch(.*)*',
        component: () => import('@/components/ErrorMessage/404.vue'),
    }
]

标签:No,URL,next,item,报错,path,router,路由
From: https://www.cnblogs.com/wanglei1900/p/16950047.html

相关文章

  • nodejs新版本引起的:digital envelope routines::unsupported
    一、起因由于电脑重装系统,重新下载nodejs,自然更新到最新版本18,之前的版本才16。更新到最新nodejs版本后,运行vue文件,报错:this[kHandle]=new_Hash(algorithm,xofLen);......
  • node js中的buffer
    Node中Buffer的深度解析Node中Buffer的深度解析在Node中,应用需要处理网络协议、操作数据库、处理图片、接收上传文件等,在网络流和文件的操作中,还要处理大量二进制数据,Jav......
  • nodejs express报错request entity too large
    今天在做上传图的功能时遇到报错413PayloadTooLarge; expressdeprecatedres.send(status):Useres.sendStatus(status)insteadindex.js:18:13PayloadTooLargeErr......
  • NOIP2022 T1 种花 题解
    Part1吐槽&退役寄考场上唯一AC的题目,T3看错题以为可以删去不止1条边,T4输出没换行,寄。最后喜提100+0+0+0,给我的OI生涯画上了一个不完美的句号。Part2题解题目让统计......
  • noi 1.5 39 与7无关的数
    noi1.539 与7无关的 数 。1.描述一个正整数,如果它能被7整除,或者它的十进制表示法中某一位上的数字为7,则称其为与7相关的数.现求所有小于等于n(n<100)的与7......
  • 使用NodeMcu(ESP-12E)的串口通信淘晶驰串口屏
    目录1.背景2.准备工作-硬件准备-软件准备3.程序编写-串口屏-NodeMcu总结1.背景没有原因,我开心。2.准备工作-硬件准备NODEMCU(NodeMcu官网)选用的IO......
  • P8865 [NOIP2022] 种花
    P8865NOIP2022种花-洛谷|计算机科学教育新生态(luogu.com.cn)。记\(a(x,y)\)代表原文的\(a_{x,y}\)。考虑对每个点统计:左上角在该点的\(\texttt{C-}\),\(\te......
  • P8866 [NOIP2022] 喵了个喵
    P8866NOIP2022喵了个喵-洛谷|计算机科学教育新生态(luogu.com.cn)。本题解中我们将图案为\(x\)的卡牌看做数字\(x\),将本题对于卡牌的操作看做对数字的操作。观......
  • css: normalize.css
     <!doctypehtml><html><head><metacharset="utf-8"><metaname="viewport"content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.......
  • 「V 曲闲谈」《一半的梦》——“模糊”&「NOIP 2022」未游之记
      好久没写闲谈了欸。现在雨兔正坐在家里的台式机前,开着腾讯会议监控自习,但是她悄悄打开记事本,bilibili单曲循环《一半的梦》(系统Vol=2,兔耳朵真好使)。  感谢Rainy7......