业务场景描述:
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
}
]
}
]
});
问题
- 动态添加子路由有没有什么更好的方式
- addRoutes能实现删除路由么?(其实这里最好的方法是不用路由,把子菜单维护一个后端传的数组就行,但是我就想奔着这个方向去研究,这只是我自己玩的一个demo)
-
重点 当我成功添加完子路由后,会出现这样的情况,文字感觉不好描述,就直接上图片了(这点我真不明白):
把你的父路由也配里面就行了