路由嵌套分析
- 点击父级路由链接显示模板内容
- 模板内容中又有子级路由链接
- 点击子级路由链接显示子级模板内容
默认显示
点击 hello链接显示 本身的组件外,还显示了自身下的子组件
嵌套路由用法
父路由组件模板
-
父路由链接
-
父路由填充位
<div id="app">
<router-link to="/index">index</router-link>
<router-link to="/hello">hello</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
子级路由组件模板
- 子级路由链接
- 子级路由填充位
const hello = {
template: `<div>
<h1>hello 组件</h1>
<hr/>
<!-- 子路由链接 -->
<router-link to="/hello/tab1">tab1</router-link>
<router-link to="/hello/tab2">tab2</router-link>
<!-- 子路由的占位符 -->
<router-view />
<div>`
}
嵌套路由的配置
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
//重定向路由(默认显示一个内容)
{ path: '/', redirect: '/index'},
{ path: '/index', component: index },
// children 数组表示子路由规则
{ path: '/hello', component: hello, children: [
{ path: '/hello/tab1', component: Tab1 },
{ path: '/hello/tab2', component: Tab2 }
] }
]
})
好了,这样就结束整个操作了,具体操作请看下面案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="vue.js"></script>
<script src="vue-router.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/index">index</router-link>
<router-link to="/hello">hello</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const index = {
template: '<h1>index 组件</h1>'
}
const hello = {
template: `<div>
<h1>hello 组件</h1>
<hr/>
<!-- 子路由链接 -->
<router-link to="/hello/tab1">tab1</router-link>
<router-link to="/hello/tab2">tab2</router-link>
<!-- 子路由的占位符 -->
<router-view />
<div>`
}
const Tab1 = {
template: '<h3>tab1 子组件</h3>'
}
const Tab2 = {
template: '<h3>tab2 子组件</h3>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
//重定向路由(默认显示一个内容)
{ path: '/', redirect: '/index'},
{ path: '/index', component: index },
// children 数组表示子路由规则
{ path: '/hello', component: hello, children: [
{ path: '/hello/tab1', component: Tab1 },
{ path: '/hello/tab2', component: Tab2 }
] }
]
})
// 创建 vm 实例对象
const vm = new Vue({
el: '#app',
data: {},
// 挂载路由实例对象
router
})
</script>
</body>
</html>
结果
打开浏览器默认显示
点击“hello”链接后显示
点击“hello”链接下的“tab2”链接后显示
至此整个流程就梳理完成了