1蕾各、創(chuàng)建一個(gè)首頁(yè)組件,并通過(guò)路由在根實(shí)例中顯示:
<body>
<div id="app">
<router-view></router-view>
</div>
<script type="text/x-template" id="home">
<div>
<h2>我是首頁(yè)模版</h2>
</div>
</script>
<script>
//首頁(yè)組件
var home = {
template:'#home'
};
var router = new VueRouter({
routes:[
{
path:'/',
component:home
}
]
});
new Vue({
el:'#app',
router
})
</script>
</body>
2庆揪、創(chuàng)建另外兩個(gè)子組件
<script type="text/x-template" id="son1">
<div>
<h2>我是子組件1模版</h2>
</div>
</script>
<script type="text/x-template" id="son2">
<div>
<h2>我是子組件2模版</h2>
</div>
</script>
//子組件1
var son1 = {
template:'#son1'
};
//子組件2
var son2 = {
template:'#son2'
};
3式曲、給首頁(yè)組件添加這兩個(gè)子組件,首先要在首頁(yè)組件中添加router-link缸榛,使其能指向子組件吝羞,然后在路由規(guī)則中首頁(yè)的路由規(guī)則中添加children屬性兰伤,并配置兩個(gè)子組件的路由規(guī)則,最后要在首頁(yè)組件模版中添加router-view來(lái)展示兩個(gè)子組件的內(nèi)容
注
子組件的內(nèi)容要在父組件中的router-view中展示
<script type="text/x-template" id="home">
<div>
<h2>我是首頁(yè)模版</h2>
<router-link to="/son1">子組件1</router-link>
<router-link to="/son2">子組件2</router-link>
<router-view></router-view>
</div>
</script>
var router = new VueRouter({
routes:[
{
path:'/',
component:home,
children:[
{
path:'/son1',
component:son1
},
{
path:'/son2',
component:son2
}
]
}
]
});
路由當(dāng)中的回退
可以在組件當(dāng)中添加a標(biāo)簽:
//.prevent修飾可以阻止a標(biāo)簽本身的跳轉(zhuǎn)刷新
<a href="" @click.prevent="goBack">回退</a>
然后在對(duì)應(yīng)的組件中添加方法:
methods:{
goBack(){
this.$router.back(-1)
}
}
默認(rèn)路由
當(dāng)所有的路由規(guī)則都不匹配時(shí)脆贵,可以添加一個(gè)默認(rèn)路由(配置404頁(yè)面):
//定義一個(gè)頁(yè)面找不到的組件
var notFound = {
template:'<h2>該頁(yè)面找不到了医清。。卖氨。</h2>'
};
{
path:'*',
component:notFound
}