服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - vue路由结构可设一层方便动态添加路由操作

vue路由结构可设一层方便动态添加路由操作

2021-09-06 17:26一行注释 JavaScript

这篇文章主要介绍了vue路由结构可设一层方便动态添加路由操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

动态添加路由基本功能

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

this.$router.addRoutes(routes)

涉及多层路由嵌套 如图

vue路由结构可设一层方便动态添加路由操作

单纯使用addRoutes 层级结构不同

修改路由结构

例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
     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,
      },
      
     ]
},

修改单一结构

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
{
     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

?
1
2
3
4
5
6
7
8
9
10
11
12
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

?
1
2
3
4
5
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路由结构可设一层方便动态添加路由操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_37818095/article/details/107067372

延伸 · 阅读

精彩推荐