前言

本篇文章介绍vue如何动态添加子路由。


动态添加子路由

动态添加子路由还是用addRoutes这个api来实现:addRoutes

实现步骤:

1、先通过路由树获取到当前根路由(routeBse)与当前路由(selfRoute)。

/**
* 路由树: this.$store.state.permission.routes  因为路由树是动态生成的 我把它存在了vuex中
* api:$route.matched  一个数组,可以获取到父路由到当前路由的层级。matched
*/

const routeBase = this.$store.state.permission.routes.find(r => r.name === this.$route.matched[0].name)
const selfRoute = this.$route.matched[this.$route.matched.length - 1]

2、声明pushRoute函数,从根路由开始遍历找到当前路由,然后在当前路由的父路由.children.push需要添加的子路由。最后addRoutes[根路由],就完事了。

/** pushRoute函数
* 参数:base  根路由
* 参数:baseFather 当前路由父路由
* 参数:route 需要添加的子路由
* 参数:self 当前路由
*/

const routeBase = this.$store.state.permission.routes.find(r => r.name === this.$route.matched[0].name)
const selfRoute = this.$route.matched[this.$route.matched.length - 1]

const route = {
    name: 'test',
    path: 'test',
    component: component
}


pushRoute(routeBase, null, route, selfRoute)
this.$router.addRoutes([routeBase])

// 将路由添加到当前路由的同级
function pushRoute(base, baseFather, route, self) {
  if (base.name === self.name) {
    if (baseFather.children.find(r => r.name === route.name)) { // 已存在路由不会重复添加
      return
    }
    // 添加
    baseFather.children.push(route)
  } else {
    if (base.children) {
      base.children.forEach(b => {
        // 递归调用
        pushRoute(b, base, route, self)
      })
    }
  }
}

注意:实际上addRoutes添加根路由并不会重复添加已存在的路由,vue底层会自动过滤已注册的路由并将warning输出到控制台上。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐