如何用addRoutes实现子路由动态添加?这里有我不完善的实现思路和遇到的问题

业务场景描述:

图片描述
图片描述

app.vue 入口文件,就只有一个router-view,用于承载login.vue

<template lang="html">
  <div id="app">
    <router-view></router-view>
  </div>
</template>

login.vue就一个链接跳转,到/dashboard

dashboard.vue 在这里还有一个router-view用于承载每个子路由的视图。

addRoute()是我添加子路由的方式,但是浏览器会warn,很明显是因为路由重复了,只不过vue-router好像自动去重了,因为我打印this.$router里面的路由是正确的。但是这种方式总归不好,有没有更好的方式啊?
图片描述

<template lang="html">
  <div class="dashboard-page">
    <aside>
      <router-link v-for="item in menuItem" :to="{ name: item.name}"  :key="item.path">{{item.name}}</router-link>
    </aside>
    <Form ref="formInline" class="pull-right add-item">
      <Input type="text" v-model="itemName"></Input>
      <Button @click="addRoute">添加</Button>
    </Form>
    <router-view></router-view>
  </div>
</template>

<script>
import temp from '@/components/temp';
export default {
  name: 'dashboardPage',
  data() {
    return {
      itemName: '',
    }
  },
  computed: {
    menuItem() {
      return this.$store.state.routes.children;
    },
    menuItemLength() {
      return this.$store.state.routes.children.length;
    }
  },
  methods: {
    addRoute() {
      const routes = {
        path: `/dashboard/menuItem-${this.menuItemLength + 1}`,
        name: this.itemName,
        component: temp
      }
      this.$store.commit('addRoute', routes);
      this.$router.addRoutes(this.$store.state.routes.children.concat(routes));
    }
  }
}
</script>

vuex: store.js

这里主要是用来存储子菜单,用于dashboard.vue中的router-link遍历,其实和router.js的路由没什么关联。

router.js,需要实现的需求就是addRoute添加/dashboard的子路由

export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      components: { page: dashboard},
      children: [
        {
          path: 'presonal',
          name: '个人',
          component: presonal
        }
      ]
    }
  ]
});

问题

  1. 动态添加子路由有没有什么更好的方式
  2. addRoutes能实现删除路由么?(其实这里最好的方法是不用路由,把子菜单维护一个后端传的数组就行,但是我就想奔着这个方向去研究,这只是我自己玩的一个demo)
  3. 重点 当我成功添加完子路由后,会出现这样的情况,文字感觉不好描述,就直接上图片了(这点我真不明白):
    图片描述
阅读 22.1k
7 个回答

把你的父路由也配里面就行了

新手上路,请多包涵

我遇到了跟你一样的问题

单看效果的话我觉得
1.dashboard.vue应该单独插在一个<router-view></router-view>
2.个人和故事应该插在另一个<router-view></router-view>,导航路由时只切换这个槽的展示

原来

        var data = [{
          path: '/deviceManage/deviceManage',
          name: 'deviceManage',
          component: deviceManage
        }]
        this.$router.addRoutes(data)

加上父路由以后的:

        var data = [{
          path: '/deviceManage',
          name: 'device',
          component: home,
          children: [{
            path: '/deviceManage/deviceManage',
            name: 'deviceManage',
            component: deviceManage
          }]
        }]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题