- 路由的基本配置
- 基本參數(shù)
- path
路由的訪問(wèn)路徑。即url - component
訪問(wèn)路徑對(duì)應(yīng)的組件
- path
- 擴(kuò)展參數(shù)
- name
路由指定命名,設(shè)置后可用params傳參及使用name進(jìn)行路由跳轉(zhuǎn)
- name
- 基本參數(shù)
實(shí)現(xiàn)敲localhost:8080/home展示home.vue內(nèi)容
1.在src/router/index.js里(vue-cli3是一個(gè)放在外部的配置文件)
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/home' ,
component: () => import('../views/Home.vue'),//懶加載
}
]
})
2.要再app.vue中加:

image.png
原因:在main.js中

image.png
- 路由的跳轉(zhuǎn)
- router-link標(biāo)簽跳轉(zhuǎn)(相當(dāng)于a標(biāo)簽)
- 編程式導(dǎo)航
// route可以是對(duì)象,或者是字符串
// 對(duì)象的時(shí)候可通過(guò)路由的path或者name進(jìn)?跳轉(zhuǎn)
// 字符串的話只能是路由的path
this.$router.push(route)
// 路由傳遞參數(shù), query和path配合, params和name配合
query: this.$router.push({path: '/', query: {id: 2}})
params: this.$router.push({name: 'home', params: {id: 2}})
1.點(diǎn)擊home文件會(huì)跳轉(zhuǎn)home.vue

image.png
2.用函數(shù)式編程實(shí)現(xiàn)

image.png
- 動(dòng)態(tài)路由
- 組件是同一個(gè),只是通過(guò)不同的url參數(shù)渲染不同的數(shù)據(jù)
- 路徑參數(shù)"使用冒號(hào)":標(biāo)記
- 在path里顯示聲明后,通過(guò)params傳參后,參數(shù)不丟失同時(shí)參數(shù)被設(shè)置成必傳參數(shù)
{
path: '/home/:id',
component: home
}
使用場(chǎng)景:依據(jù)用戶不同ID跳轉(zhuǎn)不同的頁(yè)面

image.png

image.png
這個(gè)時(shí)候輸入“l(fā)ocalhost:8080/home/123456”,會(huì)在頁(yè)面中顯示123456
- 嵌套路由
- 目的:組件中嵌套不同組件
- 實(shí)現(xiàn)
// 在需要嵌套的路由中補(bǔ)充children字段
{
path: '/home/:id',
component: home,
children: []
}
例子:實(shí)現(xiàn)在home.vue中展示child.vue中的內(nèi)容
1:在home.vue中加<router-view>
2:

image.png
- 守衛(wèi)導(dǎo)航
- 通過(guò)router中的beforeEach注冊(cè)全局守衛(wèi),每次切換路由是觸發(fā)
在main.js中寫
- 通過(guò)router中的beforeEach注冊(cè)全局守衛(wèi),每次切換路由是觸發(fā)
// to, from是路由對(duì)象,我們?cè)诼酚?定義的參數(shù)都可以在這?取到,例如to.path或
from.name
router.beforeEach((to, from, next) => {
// ...
next()
})
to: 將進(jìn)入的路由對(duì)象
from: 將離開的路由對(duì)象
next() 確認(rèn)完成操作,最后一定要調(diào)用,不然路由就不會(huì)進(jìn)行切換