【VueRouter】router.addRoutes
zh-rocco opened this issue · comments
说明:动态添加更多的路由规则
// router.js
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: () => import(/* webpackChunkName: "home" */ './views/Home.vue'),
},
{
path: '/about',
name: 'about',
component: () => import(/* webpackChunkName: "about" */ './views/About.vue'),
},
{
path: '*',
redirect: '/',
},
],
});
App.vue
<template>
<div id="app">
<div id="nav">
<router-link v-for="r in routes"
:key="r.path"
:to="r.path">{{ r.name }}</router-link>
</div>
<router-view/>
<button @click="addRoutes">add routes</button>
</div>
</template>
<script>
const AsyncComponent = () => import(/* webpackChunkName: "async" */ '@/views/Async');
export default {
name: 'app',
data() {
return {
routes: [{ name: 'Home', path: '/' }, { name: 'About', path: '/about' }],
};
},
computed: {
routeMap() {
return this.routes.reduce((accu, curr) => {
accu[curr.name] = curr.path;
return accu;
}, {});
},
},
methods: {
addRoutes() {
if (this.routeMap.Async) return;
this.$router.addRoutes([
{
path: '/async',
component: AsyncComponent,
},
]);
this.routes.push({ name: 'Async', path: '/async' });
},
},
};
</script>