温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在vue路由结构中如何实现动态添加路由

发布时间:2020-11-06 15:47:59 来源:亿速云 阅读:592 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关在vue路由结构中如何实现动态添加路由,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

动态添加路由基本功能

let routes=[{ path: '/login', name: 'login', component: () => import('../components/Login.vue') }]

this.$router.addRoutes(routes)

涉及多层路由嵌套 如图

在vue路由结构中如何实现动态添加路由

单纯使用addRoutes 层级结构不同

修改路由结构

例:

{
     name:'account',
     path: '/account/account',
     meta: {
      title: '个人中心',
      requireAuth: true
     },
     component: account,
     children:[
      {
       name: 'account',
       path: '/account/account',
       meta: {
        title: '账号设置',
        requireAuth: true
       },
       component: setAccount,
      },
      {
       name: 'childMgt',
       path: '/account/childMgt',
       meta: {
        title: '子账号管理',
        requireAuth: true
       },
       component: childMgt,
      },
      
     ]
},

修改单一结构

{
     name:'account',
     path: '/account/account',
     meta: {
      title: '个人中心',
      requireAuth: true
     },
     component: account,
     children:[
      {
       name: 'account',
       path: '/account/account',
       meta: {
        title: '账号设置',
        requireAuth: true
       },
       component: setAccount,
      },
     ]
},
{
     name:'account',
     path: '/account/childMgt',
     meta: {
      title: '个人中心',
      requireAuth: true
     },
     component: account,
     children:[
      {
       name: 'userMgt',
       path: '/account/childMgt',
       meta: {
        title: '子账号管理',
        requireAuth: true
       },
       component: childMgt,
      },
     ]
},

每一层单独包含一个子集合方便权限管理动态添加

main.js

router.beforeEach((to, from, next) => {
 if (from.name == null) { //页面刷新
 let pathName = sessionStorage.getItem("pathName") //暂存上一个路由
 if (pathName == to.path||pathName==to.redirectedFrom) {
 } else {
  sessionStorage.setItem("pathName", to.redirectedFrom)
 }
 } else {
  sessionStorage.setItem("pathName", to.path)
 }
 next()
})

app.vue

let routes=[处理后路由信息]
this.$router.addRoutes(routes)
this.$nextTick(i=>{
  this.$router.replace(sessionStorage.getItem("pathName"))//跳转指定地址 否则404
})

补充知识:vue路由进入下一层返回上一层重复跳转之前进入页面

说明

vue路由返回上一层,使用 this.$router.back(-1)

进入其他页面用 this.$outer.push('home')

这样当我进入页面会发生如下场景

进入页面时:A-B-C

返回页面时:C-B-A

总的路径行程:A-B-C-B-A

总的来是:页面返回时重复返回上一层

解决

官方文档

在vue路由结构中如何实现动态添加路由

this.$outer.push('home') // 会重复添加路由信息进入路由记录

this.$outer.replace('home') // 会替换之前的路由记录

this.$outer.replace('home') // 跳转页面推荐用这个

以上就是在vue路由结构中如何实现动态添加路由,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI