一篇超詳細(xì)的Vue-Router手把手教程
最近在重溫vue全家桶,再看一遍感覺(jué)記憶更深刻,所以專(zhuān)門(mén)記錄一下(本文vue-router版本為v3.x)。
1,router-view
<router-view>是一個(gè)功能性組件,用于渲染路徑匹配到的視圖組件。可以配合<transition>和<keep-alive>使用。如果兩個(gè)一起用,要確保在內(nèi)層使用<keep-alive>。
<router-view></router-view> <!--或--> <router-view name="footer"></router-view>
如果 <router-view>設(shè)置了名稱(chēng),則會(huì)渲染對(duì)應(yīng)的路由配置中 components下的相應(yīng)組件。
2,router-link
<router-link>標(biāo)簽支持用戶在具有路由功能的應(yīng)用中(點(diǎn)擊)導(dǎo)航。
屬性 | 類(lèi)型 | 說(shuō)明 |
---|---|---|
to | String/Object | 目標(biāo)路由/目標(biāo)位置的對(duì)象 |
replace | Boolean | 不留下導(dǎo)航記錄 |
append | Boolean | 在當(dāng)前路徑后加路徑 /a => /a/b |
tag | String | 指定渲染成何種標(biāo)簽 |
active-class | String | 激活時(shí)使用的Class |
<router-link :to="{ path: '/login'}" replace tag="span"></router-link>
3,重定向redirect
根路由重定向到login
const router = new VueRouter({ routes: [ { path: '/', redirect: '/login' } ] })
動(dòng)態(tài)返回重定向目標(biāo)
const router = new VueRouter({ routes: [ { path: '/a', redirect: to => { // 方法接收 目標(biāo)路由 作為參數(shù) // return 重定向的 字符串路徑/路徑對(duì)象 }} ] })
4,路由別名
路由訪問(wèn)/b時(shí),URL會(huì)保持為/b,但是路由匹配則為/a
const router = new VueRouter({ routes: [ { path: '/a', component: A, alias: '/b' } ] })
5,路由傳參props
使用props,避免和$route過(guò)度耦合,這樣就可以直接在組件中使用props接收參數(shù)
5.1,布爾模式
在路由后面寫(xiě)上參數(shù),并設(shè)置props為true
{ path: '/vuex/:id', name: 'Vuex', component: () => import('@/view/vuex'), props: true, mate: { title: 'vuex' } }
設(shè)置跳轉(zhuǎn)需要傳遞的參數(shù)params
<router-link :to="{name:'Vuex', params: {id: '99999'}}" tag="h1">跳轉(zhuǎn)</router-link> <!--或者--> toNext() { this.$router.push({ name: 'Vuex', params: { id: '99999' } }) }
在跳轉(zhuǎn)過(guò)去的頁(yè)面,通過(guò)props或者this.$params取參
props: { id: { type: String, default: '' } } <!--或者--> this.$params.id
5.2,對(duì)象模式
在路由中設(shè)置props為對(duì)象,攜帶靜態(tài)數(shù)據(jù)
{ path: '/vuex', name: 'Vuex', component: () => import('@/view/vuex'), props: { id: '99999' }, mate: { title: 'vuex' } }
跳轉(zhuǎn)
<router-link :to="{name:'Vuex'}" tag="h1">跳轉(zhuǎn)</router-link> <!--或者--> toNext() { this.$router.push({ name: 'Vuex' }) }
在跳轉(zhuǎn)過(guò)去的頁(yè)面,通過(guò)props或者this.$params取參
props: { id: { type: String, default: '' } } <!--或者--> this.$params.id
注意:只適用于靜態(tài)數(shù)據(jù)
5.3,函數(shù)模式
先在路由中設(shè)置props為Function,return一個(gè)對(duì)象,不管是query傳參還是params傳參,都可以轉(zhuǎn)為props
{ path: '/vuex', name: 'Vuex', component: () => import('@/view/vuex'), props: route => ({ <!--query--> id: route.query.id, <!--params--> age: route.params.age }), mate: { title: 'vuex' } }
跳轉(zhuǎn)
<router-link :to="{name:'Vuex',query: {id: '99999'}, params:{age:'20'}}" tag="h1">跳轉(zhuǎn)</router-link> <!--或者--> toNext() { this.$router.push({ name: 'Vuex', query: { id: '999999' }, params: { age: '20' } }) }
在跳轉(zhuǎn)過(guò)去的頁(yè)面,通過(guò)props或者this.$route.params / this.$route.query取參
props: { id: { type: String, default: '' }, age: { type: String, default: '' } } <!--或者--> this.$route.query this.$route.params
6,路由守衛(wèi)
路由守衛(wèi)主要用來(lái)通過(guò)跳轉(zhuǎn)或取消的方式守衛(wèi)導(dǎo)航。
6.1,全局前置守衛(wèi)beforeEach
當(dāng)一個(gè)導(dǎo)航觸發(fā)時(shí),全局前置守衛(wèi)按照創(chuàng)建順序調(diào)用。守衛(wèi)是異步解析執(zhí)行,此時(shí)導(dǎo)航在所有守衛(wèi)解析完之前一直處于等待中。
參數(shù) | 說(shuō)明 |
---|---|
to | 即將要進(jìn)入的目標(biāo)路由對(duì)象 |
from | 當(dāng)前導(dǎo)航正要離開(kāi)的路由 |
next | 回調(diào)方法 |
next用法如下
語(yǔ)法 | 說(shuō)明 |
---|---|
next() | 進(jìn)行下一個(gè)鉤子 |
next(false) | 中斷導(dǎo)航,URL如已改,則重置到from的地址 |
next('/') | 中斷當(dāng)前跳轉(zhuǎn)并到其他地址,可設(shè)置路由對(duì)象 |
next(error) | 導(dǎo)航終止并傳遞錯(cuò)誤給onError() |
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
6.2,全局解析守衛(wèi)beforeResolve
2.5.0新增,和beforeEach類(lèi)似,區(qū)別是在導(dǎo)航被確認(rèn)之前,同時(shí)在所有組件內(nèi)守衛(wèi)和異步路由組件被解析之后,解析守衛(wèi)就被調(diào)用。
router.eforeResolve((to, from, next) => { // ... })
6.3,全局后置鉤子afterEach
后置守衛(wèi)不會(huì)接受next函數(shù)也不會(huì)改變導(dǎo)航本身
router.afterEach((to, from) => { // ... })
6.4,路由獨(dú)享守衛(wèi)beforeEnter
可以在路由配置上直接定義專(zhuān)屬的beforeEnter守衛(wèi),與全局前置守衛(wèi)的方法參數(shù)是一樣的。
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })
6.5,組件內(nèi)的守衛(wèi)
- beforeRouteEnter
該守衛(wèi)不能訪問(wèn)this,因?yàn)槭匦l(wèi)在導(dǎo)航確認(rèn)前被調(diào)用,因此即將登場(chǎng)的新組件還沒(méi)被創(chuàng)建??梢酝ㄟ^(guò)傳一個(gè)回調(diào)給next來(lái)訪問(wèn)組件實(shí)例。在導(dǎo)航被確認(rèn)的時(shí)候執(zhí)行回調(diào),并且把組件實(shí)例作為回調(diào)方法的參數(shù)。
const Footer = { template: `...`, beforeRouteEnter(to, from, next) { next(vm => { // 通過(guò) `vm` 訪問(wèn)組件實(shí)例 }) } }
- beforeRouteUpdate (2.2 新增)
在當(dāng)前路由改變,但是該組件被復(fù)用時(shí)調(diào)用,可以訪問(wèn)組件實(shí)例this。
const Foo = { template: `...`, beforeRouteUpdate(to, from, next) { this.name = to.params.name next() } }
- beforeRouteLeave
導(dǎo)航離開(kāi)該組件的對(duì)應(yīng)路由時(shí)調(diào)用,通常用來(lái)禁止用戶在還未保存修改前突然離開(kāi)。可以通過(guò)next(false)來(lái)取消。
const Foo = { template: `...`, beforeRouteLeave(to, from, next) { const answer = window.confirm('確認(rèn)要離開(kāi)嗎') if (answer) { next() } else { next(false) } } }
6.6,完整的導(dǎo)航解析流程
- 導(dǎo)航被觸發(fā)。
- 在失活的組件里調(diào)用beforeRouteLeave守衛(wèi)。
- 調(diào)用全局的beforeEach守衛(wèi)。
- 在重用的組件里調(diào)用beforeRouteUpdate守衛(wèi) (2.2+)。
- 在路由配置里調(diào)用beforeEnter。
- 解析異步路由組件。
- 在被激活的組件里調(diào)用beforeRouteEnter。
- 調(diào)用全局的beforeResolve守衛(wèi)(2.5+)。
- 導(dǎo)航被確認(rèn)。
- 調(diào)用全局的afterEach鉤子。
- 觸發(fā)DOM更新。
- 調(diào)用beforeRouteEnter守衛(wèi)中傳給next的回調(diào)函數(shù),創(chuàng)建好的組件實(shí)例會(huì)作為回調(diào)函數(shù)的參數(shù)傳入。
7,路由元信息
定義路由的時(shí)候可以配置meta對(duì)象字段,用來(lái)存儲(chǔ)每個(gè)路由對(duì)應(yīng)的信息。通過(guò)this.$route.meta來(lái)訪問(wèn),或者在路由守衛(wèi)中通過(guò)to.meta和from.meta訪問(wèn)。
const router = new VueRouter({ routes: [ { path: '/index', name: 'Index', component: () => import('@/view/index'), meta: { title: '首頁(yè)', rolu: ['admin', 'boss'] } } ] })
8,過(guò)渡動(dòng)效
只需要使用transition標(biāo)簽包裹住router-view標(biāo)簽即可,動(dòng)畫(huà)效果可以自己定義,參考transition組件的用法。也可以在父組件或者app.js中使用watch監(jiān)聽(tīng)$route變化,根據(jù)不同路由替換transition組件的name屬性,實(shí)現(xiàn)不同的動(dòng)畫(huà)效。
<transition :name="transitionName"> <router-view></router-view> </transition>
監(jiān)聽(tīng)
watch: { '$route' (to, from) { const toD = to.path.split('/').length const fromD = from.path.split('/').length this.transitionName = toD < fromD ? 'slide-right' : 'slide-left' } }
9,滾動(dòng)行為
當(dāng)創(chuàng)建Router實(shí)例時(shí),可以提供一個(gè)scrollBehavior方法,并接收to和from路由對(duì)象。第三個(gè)參數(shù)savedPosition只有通過(guò)瀏覽器的前進(jìn)/后退按鈕觸發(fā)時(shí)才可用。
const router = new VueRouter({ mode: 'hash', routes, scrollBehavior(to, from, savedPosition) { if (savedPosition) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(savedPosition) }, 1000) }) } else { return { x: 0, y: 0 } } } })
10,完整路由配置
首先導(dǎo)入Vue和vue-router,然后使用router,定義路由信息集合,每個(gè)路由都是一個(gè)對(duì)象,對(duì)象擁有如下屬性
屬性 | 類(lèi)型 | 值 |
---|---|---|
path | String | 組件路徑信息 |
name | String | 組件命名 |
component | Function | 組件 |
mate | Object | 元信息 |
children | Object | 子路由 |
redirect | String | 重定向 |
props | Boolean/Object/Function | 參數(shù)傳遞 |
具體代碼如下:
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', redirect: '/index' }, { path: '/index', name: 'Index', component: () => import(/* webpackChunkName: "index" */ '@/view/index'), mate: { title: '首頁(yè)', auth: false } }, { path: '/login', name: 'Login', component: () => import(/* webpackChunkName: "login" */ '@/view/login'), meta: { title: '登錄', auth: false }, children: [ { path: 'children', name: 'Children', component: () => import(/* webpackChunkName: "children" */ '@/view/children'), mate: { title: '嵌套的子路由', auth: false } } ] } ] const router = new VueRouter({ mode: 'hash', routes }) export default router
注意:嵌套子路由必須在被嵌套的頁(yè)面放置<router-view>標(biāo)簽。
總結(jié)
到此這篇關(guān)于Vue-Router教程的文章就介紹到這了,更多相關(guān)Vue-Router手把手教程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決antd的Form組件setFieldsValue的警告問(wèn)題
這篇文章主要介紹了解決antd的Form組件setFieldsValue的警告問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10vite5+vue3+?import.meta.glob動(dòng)態(tài)導(dǎo)入vue組件圖文教程
import.meta.glob是Vite提供的一個(gè)特殊功能,它允許你在模塊范圍內(nèi)動(dòng)態(tài)地導(dǎo)入多個(gè)模塊,這篇文章主要給大家介紹了關(guān)于vite5+vue3+?import.meta.glob動(dòng)態(tài)導(dǎo)入vue組件的相關(guān)資料,需要的朋友可以參考下2024-07-07vue?文件切片上傳的項(xiàng)目實(shí)現(xiàn)
本文主要介紹了vue?文件切片上傳的項(xiàng)目實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03VUE中filters過(guò)濾器的兩種用法實(shí)例
vue中過(guò)濾器的作用可被用于一些常見(jiàn)的文本格式化,也就是修飾文本,但是文本內(nèi)容不會(huì)改變,下面這篇文章主要給大家介紹了關(guān)于VUE中filters過(guò)濾器的兩種用法,需要的朋友可以參考下2022-04-04Vue實(shí)現(xiàn)購(gòu)物車(chē)詳情頁(yè)面的方法
這篇文章主要介紹了Vue實(shí)戰(zhàn)之購(gòu)物車(chē)詳情頁(yè)面的實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08Element-UI中關(guān)于table表格的那些騷操作(小結(jié))
這篇文章主要介紹了Element-UI中關(guān)于table表格的那些騷操作(小結(jié)),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08vue項(xiàng)目實(shí)現(xiàn)一鍵網(wǎng)站換膚效果實(shí)例(webpack-theme-color-replacer的使用)
換皮膚一般都是點(diǎn)擊一個(gè)按鈕彈出一些皮膚的選項(xiàng),選中選項(xiàng)后皮膚生效,下面這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目實(shí)現(xiàn)一鍵網(wǎng)站換膚效果的相關(guān)資料,文中主要介紹的是webpack-theme-color-replacer的使用,需要的朋友可以參考下2023-02-02用v-html解決Vue.js渲染中html標(biāo)簽不被解析的問(wèn)題
這篇文章主要給大家介紹了如何利用v-html解決Vue.js渲染過(guò)程中html標(biāo)簽不能被解析,html標(biāo)簽顯示為字符串的問(wèn)題,文中通過(guò)圖文介紹的很詳細(xì),有需要的朋友們可以參考借鑒,下面來(lái)一起看看吧。2016-12-12