vue3动态路由,路由拦截,从接口获取路由数据

作者:zeke | 时间:Dec 9, 2024 4:23:44 PM | 访问量:4

<p>​</p><p>鉴于多人遇到这个问题,22年10月17日做修改</p><p>一、准备工具和原料</p><p>1.vue:3.0</p><p>2.pinia或者vuex,作者以pinia为例子,主要是用来缓存</p><p>3.路由拦截</p><p>二、问题说明和解决</p><p>我需要实现的功能:用vue-router的路由守卫,配置动态路由。以便于控制前端界面的权限。</p><p>遇到的问题是:增加路由后,进入对应的路由界面,没有成功,显示空白界面、或者404界面(如果配置404路由);</p><p>在控制台看到这么一小行字。</p><pre class="ql-syntax" spellcheck="false">[Vue Router warn]: No match found for location with path "/menu" </pre><p><span style="background-color: rgba(220, 220, 220, 0.5);"><img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" height="15" width="15"></span></p><p>意思是,路由没有找到/menu这个菜单。</p><p>但是我确实在动态路由加进去了。(注意:如果是后台管理界面,需要加到对应的<strong>子路由</strong>)</p><p>直接上代码吧,不懂的可以交流</p><pre class="ql-syntax" spellcheck="false">router.beforeEach(async(to: RouteLocationNormalized, from: RouteLocationNormalized, next: any) =&gt; { //状态管理工具 pinia const store = useStore() //flag标记是否请求过路由数据,可以保存在pinia或者vuex中,不必缓存 //判断flag=0并且router不存在 if(store.flag==0 &amp;&amp; !router.getRoutes().filter(it=&gt;it.path==to.path).length){ //try防止接口报错 try{ //获取路由接口数据,并且把 store.flag=1 //menuList用来缓存从接口获取的路由 store.menuList=await GetRouters(); store.flag=1 //重新进入to界面,replace: true表示浏览器不需要记录本次历史 next({ ...to, replace: true }) }catch(e){ console.log('获取菜单失败',e); store.flag=0; store.menuList=[]; //获取菜单失败,跳转登陆界面 next('/login') } }else{ next() } console.log('已有路由',router.getRoutes()); }) </pre><p><span style="background-color: rgba(220, 220, 220, 0.5);"><img src="data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==" height="15" width="15"></span></p><p>最重要的是这一句</p><p>next({ ...to, replace: true })</p><p>相当于重新进入当前界面,路由就能匹配上了</p><p>flag变量,是为了防止死循环,只在第一次进入的时候重新刷新界面。第二次就next()放行了。</p><p>OK,今天遇到的问题就总结一下。希望帮助到大家</p><p>​</p>