路由中有三個(gè)基本的概念 route, routes, router。
1. route: 是一條路由,它是單數(shù), Home按鈕 => home內(nèi)容, 這是一條route, about按鈕 => about 內(nèi)容, 這是另一條路由。
2. routes: 是一組路由,把上面的每一條路由組合起來(lái),形成一個(gè)數(shù)組。[{home 按鈕 =>home內(nèi)容 }, { about按鈕 => about 內(nèi)容}]
3. router: 是一個(gè)機(jī)制,相當(dāng)于一個(gè)管理者,它來(lái)管理路由。因?yàn)閞outes 只是定義了一組路由,它放在哪里是靜止的,當(dāng)真正來(lái)了請(qǐng)求,怎么辦? 就是當(dāng)用戶點(diǎn)擊home 按鈕的時(shí)候,怎么辦?這時(shí)router 就起作用了,它到routes 中去查找,去找到對(duì)應(yīng)的 home 內(nèi)容,所以頁(yè)面中就顯示了 home 內(nèi)容。
vue-router 中的路由也是基于上面的三個(gè)基本概念來(lái)實(shí)現(xiàn)的,我們只要把路徑和組件對(duì)應(yīng)起來(lái),然后在頁(yè)面中把組件渲染出來(lái)
1.頁(yè)面實(shí)現(xiàn)
在vue-router中有兩個(gè)標(biāo)簽 <router-link> 和 <router-view> 分別對(duì)應(yīng)點(diǎn)擊和顯示部分。
<router-link>點(diǎn)擊哪里 <router-view>顯示哪里,<router-link>有個(gè)屬性 to 就是說(shuō)點(diǎn)擊后去哪里 比如: <router-link to = "/login">login</router-link>
2.js中配置
定義route,是一個(gè)對(duì)象有兩部分組成:path 和 component 。path指路徑,component指組件。比如:
{ path: '/home', component: login }
兩條路由就組成一個(gè)routes:
const routes = [
{ path: '/home', component: home },
{ path: '/about', component: about }
]
最后創(chuàng)建router對(duì)路由進(jìn)行管理,由構(gòu)造函數(shù)new vueRouter()創(chuàng)建,接受routes參數(shù)。
const router = new vueRouter({
routes: [
{ path: '/home', component: home },
{ path: '/about', component: about }
]
})
配置完成后,把router注入到vue根實(shí)例中(main.js)
new Vue({
router
})
現(xiàn)在使用一下
1.建立home.vue 和 about.vue
// home.vue
<template>
<div>
<h1>home</h1>
<p>{{homeMsg}}</p>
</div>
</template>
<script>
export default {
data () {
return {
homeMsg: '我是home組件'
}
}
}
</script>
// about.vue
<template>
<div>
<h1>about</h1>
<p>{{aboutMsg}}</p>
</div>
</template>
<script>
export default {
data () {
return {
aboutMsg: '我是about組件'
}
}
}
</script>
2.在App.vue中 定義 <router-link > 和 </router-view>
<template>
<div id="app">
<!-- router-link 定義點(diǎn)擊后導(dǎo)航到哪個(gè)路徑下 -->
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
<!-- 對(duì)應(yīng)的組件內(nèi)容渲染到router-view中 -->
<router-view></router-view>
</div>
</template>
3.在router下的index.js中定義router
import Vue from 'vue'
import Router from 'vue-router'
import home from '../home.vue';
import about from "../about.vue";
Vue.use(Router)
export default new Router({
routes: [
{
path: "/home",
name: "home",
component: home,
},
{
path: "/about",
name: "about",
component: about
}
]
})
這時(shí)候有個(gè)問題,當(dāng)進(jìn)入頁(yè)面時(shí)沒有任何內(nèi)容,點(diǎn)擊后才有內(nèi)容。因?yàn)槭状芜M(jìn)入頁(yè)面,它的路徑是"/",沒有給這個(gè)路徑做相應(yīng)的配置。所以要用到重定向。所謂重定向,就是重新給它指定一個(gè)方向。
// 重定向
{
path: '/',
redirect: '/home'
}
/* 選中的樣式 */
a.router-link-active {
color: red;
}
/* 未選中的樣式 */
.gray {
color: gray
}
<router-link class="gray" to="/home">Home</router-link>