使用 children
属性实现路由嵌套
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 1. 导入 vue-router 组件库 -->
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css">
<title>Document</title>
</head>
<body>
<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:[ //路由的嵌套
{path:'login', component:login},
{path:'register', component:register}
]
}
]
})
var vm = new Vue({
el: '#app',
data: {},
methods: {},
router:router
});
</script>
</body>
</html>
效果展示: