vue2.0子路由配置和跳轉 vue-router: 巢狀路由
阿新 • • 發佈:2019-01-03
路由跳轉
<li class="nav_li" v-link="{ path: '/home/reg'}"></li><router-link to="/home/reg">註冊</router-link>
this.$route.router.go({name: 'reg', params: {status: this.$route.params.status}});
vm.$router.push({
path:"/home/reg",query: {
status: '1',
}
})
模板抽離
我們已經學習過了Vue模板的另外定義形式,使用<template></template>
<!-- 模板抽離出來 -->
<template id="home">
<div>首頁</div>
</template>
<template id="news">
<div>新聞</div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
然後js裡定義路由元件的時候:
// 1. 定義(路由)元件。
const Home = { template: '#home' };
const News = { template: '#news' };
- 1
- 2
- 3
路由巢狀
實際應用介面,通常由多層巢狀的元件組合而成。
比如,我們 “首頁”元件中,還巢狀著 “登入”和 “註冊”元件,那麼URL對應就是/home/login
和/home/reg
。
<template id="home">
<!-- 注意:元件只能有一個根元素,所以我們包裝到這個div中 -->
<div>
<h2>首頁</h2>
<router-link to="/home/login" >登入</router-link>
<router-link to="/home/reg">註冊</router-link>
<!-- 路由匹配到的元件將渲染在這裡 -->
<router-view></router-view>
</div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
這是訪問/home
後的模板,其中我們需要把/home/login
和/home/reg
渲染進來。
完成上面程式碼後,HTML結構如下圖:
- 登入和註冊2個元件
<template id="login">
<div>登入介面</div>
</template>
<template id="reg">
<div>註冊介面</div>
</template>
- 1
- 2
- 3
- 4
- 5
- 6
//定義路由元件
const Login = { template: '#login' };
const Reg = { template: '#reg' };
- 1
- 2
- 3
3.定義路由
// 2. 定義路由
const routes = [
{ path: '/', redirect: '/home' },
{
path: '/home',
component: Home,
children:[
{ path: '/home/login', component: Login},
{ path: '/home/reg', component: Reg}
]
},
{ path: '/news', component: News}
]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
注意我們在home
路由配置了它的children。這就是巢狀路由。