嵌套路由,很是常用
1.hello.vue:含有嵌套路由的页面,主要在第五六七行,第二十,二十一监听,注意监听的对象
<template>
<div class="hello">
<!--{{ this.$route.params.num }}-->
<h1>这个是hello页面,穿过的参数是{{$route.params.hparam1}}</h1>
<router-link to="/children1">children1页面</router-link>
<router-link to="/children2">children2页面</router-link>
<router-view></router-view>
<h2></h2>
</div>
</template>
<script>
export default {
name: 'hello',
data() {
return {
msg: 'this is the hello页面'
}
},
$route(to, from) {
console.log(to);
console.log(from);
},
props: ['logo']
}
</script>
2.children2.vue:hello。vue的第二个子界面。
<template>
<div class="hello">
<!--{{ this.$route.params.num }}-->
<h1>这个是hello-children2页面</h1>
<h2></h2>
</div>
</template>
<script>
export default {
name: 'hello',
data() {
return {
msg: 'this is the hello页面'
}
},
props: ['logo']
}
</script>
3.children1.vue:hello.vue的第一个子界面
<template>
<div class="hello">
<!--{{ this.$route.params.num }}-->
<h1>这个是hello-children1页面</h1>
<h2></h2>
</div>
</template>
<script>
export default {
name: 'hello',
data() {
return {
}
},
}
</script>
4.router/index:路由的配置文件,注意查看第七十六,七十七行用来配置在hello的children中。如若配置在外部,会被识别为同级
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [{
name:"/hello:param1",
path: '/hello:hparam1',
component: require('../components/Hello.vue'),
children:[
{name:"/children1",path:"/children1",component:require("./../components/children1.vue")},
{name:"/children2",path:"/children2",component:require("./../components/children2.vue")},
]
},
{
name: '/foo',
path: '/foo/:fparam1/age:fparam2',
component: require('../components/foo.vue')
},
{
path: '*',
redirect: '/hello:hparam1'
},
]
})
export default router;
5.app.vue:主页面
<template>
<div id="app">
<!-- <hello></hello> -->
<div class="nav">
<ul>
<li>
<router-link to="/hello123">hello页面</router-link>
</li>
<li>
<router-link to="/foo/mk/agehello">foo页面</router-link>
</li>
</ul>
</div>
<div class="main">
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: 'app',
components: {},
watch: {
$route(to, from) {
console.log(to);
console.log(from);
}
}
}
</script>
<style>
body {background-color: #f8f8ff;font-family: 'Avenir', Helvetica, Arial, sans-serif;color: #2c3e50;}
.nav {position: fixed;width: 108px;left: 40px;}
.nav ul {list-style: none;margin: 0;padding: 0;}
.nav ul li {width: 108px;height: 48px;line-height: 48px;border: 1px solid #dadada;text-align: center; }
.nav ul li a {display: block;position: relative;text-decoration: none;}
.nav ul li img {position: absolute; left: 0;top: 0; width: 100px;height: 30px;}
.main { height: 400px;margin-left: 180px;margin-right: 25px;}
</style>
6.main.js:配置路由的引入
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import router from './router'
Vue.use(VueRouter);
new Vue({
el: '#app',
router,
render: h => h(App)
})
界面效果如下: