一、vue-router配置子路由
实际生活中的应用界面其实更加复杂,通常由多层嵌套的组件组合而成。比如;H1页面和H2页面嵌套在主页中
1.首先用标签增加了两个新的导航链接
<router-link :to="{name:'HelloWorld'}">主页</router-link>
<router-link :to="{name:'H1'}">H1页面</router-link>
<router-link :to="{name:'H2'}">H2页面</router-link>
2.在HelloWorld.vue加入标签,给子模板提供插入位置
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<router-view></router-view>
</div>
</template>
3.在components目录下新建两个组件模板 H1.vue 和 H2.vue
两者内容类似,以下是H1.vue页面内容:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
msg: 'I am H1 page,Welcome to H1'
}
}
}
</script>
4.修改router/index.js代码,子路由的写法是在原有的路由配置下加入children字段。
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
children: [{path: '/h1', name: 'H1', component: H1},//子路由的<router-view>必须在HelloWorld.vue中出现
{path: '/h2', name: 'H2', component: H2}
]
}
]
二、单页面多路由区域操作
在一个页面里我们有两个以上区域,我们通过配置路由的js文件,来操作这些区域的内容
1.App.vue文件,在下面新写了两行标签,并加入了些CSS样式
<template>
<div id="app">
<img src="./assets/logo.png">
<router-link :to="{name:'HelloWorld'}"><h1>H1</h1></router-link>
<router-link :to="{name:'H1'}"><h1>H2</h1></router-link>
<router-view></router-view>
<router-view name="left" style="float:left;width:50%;background-color:#ccc;height:300px;"/>
<router-view name="right" style="float:right;width:50%;background-color:yellowgreen;height:300px;"/>
</div>
</template>
2.需要在路由里配置这三个区域,配置主要是在components字段里进行
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
components: {default: HelloWorld,
left:H1,//显示H1组件内容'I am H1 page,Welcome to H1'
right:H2//显示H2组件内容'I am H2 page,Welcome to H2'
}
},
{
path: '/h1',
name: 'H1',
components: {default: HelloWorld,
left:H2,//显示H2组件内容
right:H1//显示H1组件内容
}
}
]
})
上边的代码我们编写了两个路径,一个是默认的‘/’,另一个是‘/Hi’.在两个路径下的components里面,我们对三个区域都定义了显示内容。