一 、概要
vue的單頁(yè)面應(yīng)用是基于路由和組件的,路由用于設(shè)定訪問路徑,并將路徑和組件映射起來。傳統(tǒng)的頁(yè)面應(yīng)用,是用一些超鏈接來實(shí)現(xiàn)頁(yè)面切換和跳轉(zhuǎn)的。
在vue-router單頁(yè)面應(yīng)用中,則是路徑之間的切換,實(shí)際上就是組件的切換。路由就是SPA(單頁(yè)應(yīng)用)的路徑管理器
二 、基礎(chǔ)使用
1 、創(chuàng)建Router
<script>
const home = Vue.component('home', {
template: '<div><h1>首頁(yè)</h1><p v-text="msg"></p></div>',
data() {
return {
msg: '歡迎來到首頁(yè)'
}
}
});
const movies = Vue.component('movie', {
template: '<div><h1>電影</h1></div>'
});
const cinema = Vue.component('movie', {
template: '<div><h1>影院</h1></div>'
});
</script>
2、 映射路由
<script>
const routes = [
{path: '/', component: home},
{path: '/movies', component: movies},
{path: '/cinemas', component: cinema},
];
</script>
3 、創(chuàng)建 router 實(shí)例,然后傳 routes 配置
<script>
const router = new VueRouter({
routes // (縮寫) 相當(dāng)于 routes: routes
});
</script>
4、創(chuàng)建Vue實(shí)例和掛載路由。
<script>
new Vue({
el: "#app",
router,
})
</script>
5、 使用router-link指令
<div id="app">
<ul class="nav nav-pills">
<li><router-link to="/">首頁(yè)</router-link></li>
<li><router-link to="/movies">電影</router-link></li>
<li><router-link to="/cinemas">影院</router-link></li>
</ul>
</div>
6 、使用 <router-view>
<div id="app">
<router-view></router-view>
</div>
7、總結(jié)
JavaScript
- 創(chuàng)建組件:創(chuàng)建單頁(yè)面應(yīng)用需要渲染的組件
- 創(chuàng)建路由實(shí)例
- 路由列表
- 創(chuàng)建Vue實(shí)例和掛載路由
HTML
- 使用
<router-link>指令 - 使用
<router-view>標(biāo)簽
8、 <router-link>
跳轉(zhuǎn)的方式有三種
- 方式1:直接修改地址欄
- 方式2:this.$router.push(‘路由地址’)
- 方式3:
<router-link to="路由地址"></router-link>
三、流程圖

image