使用 children
屬性實現路由嵌套
<div id="app">
<router-link to="/account">Account</router-link>
<router-view></router-view>
</div>
<script>
// 父路由中的組件
const account = Vue.extend({
template: `<div>
這是account組件
<router-link to="/account/login">login</router-link> |
<router-link to="/account/register">register</router-link>
<router-view></router-view>
</div>`
});
// 子路由中的 login 組件
const login = Vue.extend({
template: '<div>登錄組件</div>'
});
// 子路由中的 register 組件
const register = Vue.extend({
template: '<div>注冊組件</div>'
});
// 路由實例
var router = new VueRouter({
routes: [
{ path: '/', redirect: '/account/login' }, // 使用 redirect 實現路由重定向
{
path: '/account',
component: account,
children: [ // 通過 children 數組屬性,來實現路由的嵌套
{ path: 'login', component: login }, // 注意,子路由的開頭位置,不要加 / 路徑符
{ path: 'register', component: register }
]
}
]
});
// 創建 Vue 實例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {},
methods: {},
components: {
account
},
router: router
});
</script>