Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the dynamic increase or decrease routing mode of vueRouter matcher?

2025-04-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

今天小编给大家分享一下vueRouter matcher动态增减路由方式是什么的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

matcher之动态增减路由

优化项目时,有个环节在主路由下,根据后端返回不同内容,需要修改动态路由。如果直接删除原来路由,再addrouter新路由,发现原来的路由还是存在的。vue动态新增路由,没有删除功能(vue官方文档好像没有提供)。

解决办法

使用matcher :

const createRouter = () => new Router({ routes: [{ path: '/', name: '登录', component: login }]const router = createRouter()export function resetRouter () { const newRouter = createRouter() router.matcher = newRouter.matcher}export default router

局部引入,在addrouter之前调用一次 resetRouter即可:

import {resetRouter} from '@/router' resetRouter(); this.$router.addRoutes(routeMenu);番外

如果需要删除添加一级路由下面单个子路由时,可以通过this.$router.options.routes获取到路由数组,通过循环方式直接进行push或splice,然后再用上面的方法进行全局替换即可。

vueRouter动态追加路由

路由分为静态路由,如事先写好的,公共的路由,如:404、login等

还有一部分是根据权限接口返回,动态追加的一些页面模块路由,如:user

在处理权限的时候,可以先允许一些不需要权限认证的路由,如下:

// 开放的路由,可以直接访问const ALLOW_ROUTES = [ '/login', '/buy', // ...];具体路由拦截全在router.beforeEach里处理

首先如果没有登录,直接跳转登录页

if (!ALLOW_ROUTES.includes(to.path) && !isLogin) { // 未登录 next({ path: '/login', replace: true }); return;}

如果已登录,使用router.addRoutes追加路由

if(isLogin && (sessionStorage.getItem('curPath') || to.matched[0].path === '*') ) { sessionStorage.removeItem('curPath'); // 还原路由(防止路由重复) router.matcher = new VueRouter({ // mode: 'history', routes }).matcher; router.addRoutes(routes: Array); // 追加路由 // util.generateMenu(); // 生成菜单,视具体情况而定 next({ path: to.path }); return;}

动态添加更多的路由规则。参数必须是一个符合 routes 选项要求的数组。

curPath用于辅助处理router.afterEach(to => { // 保存路径 if (to.path !== '/login') { sessionStorage.setItem('curPath', JSON.stringify({ path: to.path })); }})

动态路由主要是根据业务来的,不好写成一个公共的处理方式,具体在什么时候追加路由,要自己去判断,如:刷新、退出登录、重新登录、没有匹配到等操作是否满足

如果还遇到路由重复的问题,可能是在当前页push同样路由造成的,这里可以先判断一下

if(router.currentRoute.name !== 'login') { router.push({ name: 'login' })}以上就是"vueRouter matcher动态增减路由方式是什么"这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注行业资讯频道。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report