網(wǎng)站關(guān)鍵詞指數(shù)查詢seo百度貼吧
Vue Router4 匹配 Vue3;Vue Router3 匹配 Vue2。
Vue Router 是 Vue.js 官方的路由管理器。Vue Router 基于路由和組件的映射關(guān)系,監(jiān)聽頁面路徑的變化,渲染對應(yīng)的組件。
安裝:
npm install vue-router
。
基本使用:
Vue Router4 的基本使用:
// src/router/index.js
import {createRouter, createWebHashHistory} from 'vue-router'import Home from '../components/Home.vue'
import About from '../components/About.vue'// 1. 創(chuàng)建路由對象
const router = createRouter({// 配置路由映射關(guān)系,一個(gè)路徑對應(yīng)一個(gè)組件routes: [{path: '/', redirect: '/home'}, // 如果路徑是 /,重定向到 /home {path: '/home', component: Home},{path: '/about', component: About}],// 配置采用的模式history: createWebHashHistory(),
})export default router
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'const app = createApp(App)
// 2. 注冊路由對象
app.use(router)
app.mount('#app')
// 可以使用 Vue Router 提供的 <router-link> 組件實(shí)現(xiàn)路徑跳轉(zhuǎn)
// src/App.vue。
<template><!-- 3. 使用 Vue Router 提供的 <router-link> 組件實(shí)現(xiàn)路徑跳轉(zhuǎn) --><router-link to="/home">首頁</router-link><router-link to="/about">關(guān)于</router-link><!-- 4. 路徑匹配到的組件將會顯示在 <router-view> 這個(gè)占位組件處 --><router-view></router-view>
</template><script setup>
</script><style scoped>
</style> // 也可以通過代碼邏輯實(shí)現(xiàn)路徑跳轉(zhuǎn)。
// src/App.vue
<template><div><span @click="handleHomeNav">首頁</span><span @click="handleAboutNav">關(guān)于</span></div><!-- 4. 路徑匹配到的組件將會顯示在 <router-view> 這個(gè)占位組件處 --><router-view></router-view>
</template><script setup>
// 3. 通過代碼邏輯實(shí)現(xiàn)路徑跳轉(zhuǎn)
import { useRouter } from 'vue-router'
const router = useRouter()
const handleHomeNav = () => {router.push('/home')
}
const handleAboutNav = () => {router.push({path: '/about'})
}
</script><style scoped>
</style>
Vue Router3 的基本使用:
import Home form '../componnets/Home .vue'
import About form '../componnets/About .vue'// 1. 創(chuàng)建 router 實(shí)例
const router = new VueRouter({// 傳入 routes 配置定義路由routes: [{ path: 'home', component: Home },{ path: '/about', component: About }]
})
// 2. 通過 router 配置參數(shù)注入路由
const app = new Vue({router
}).$mount('#app')
<div id="app"><p><!-- 3. 使用 router-link 組件來導(dǎo)航,通過傳入 to 屬性指定鏈接 --><router-link to="/home">Home</router-link><router-link to="/about">About </router-link></p><!-- 4. router-view 是路由出口,路由匹配到的組件將渲染在這里 --><router-view></router-view>
</div>
路由對象 router:
路由對象 router 的屬性:
- history:配置路由采用的模式。屬性值有兩個(gè),createWebHashHistory 是 hash 模式,createWebHistory 是 history 模式。
- routes:配置路由映射關(guān)系。
路由對象 router 的方法:
addRoute(parentName, route)
:動態(tài)添加路由。其中的 parentName 就是配置路由映射關(guān)系 route 中獨(dú)一無二的 name 屬性,parentName 是可選的,可以通過 parentName 指定父級路由的名稱來添加嵌套的子路由。removeRoute(name)
:刪除路由。其中的 name 就是配置路由映射關(guān)系 route 中獨(dú)一無二的 name 屬性。hasRoute()
:檢查某個(gè)路由是否存在。getRoutes()
:獲取所有路由記錄。返回值是一個(gè)數(shù)組。push()
:跳轉(zhuǎn)到指定路徑。replace()
:替換掉當(dāng)前路徑。forward()
:路徑前進(jìn)一步。back()
:路徑后退一步。go()
:路徑前進(jìn)或者后退指定步數(shù)。
路由 route:
路由 route 的配置屬性:
- path:路徑。
- component:路徑匹配時(shí)要渲染的組件。
- redirect:路徑匹配時(shí)要重定向的路徑。
- name:獨(dú)一無二的路由名稱。
- children:嵌套路由。
<router-link>
組件:
<router-link>
:用于創(chuàng)建導(dǎo)航鏈接。<router-link>
的屬性有:
- to:用于指定要跳轉(zhuǎn)的路徑。屬性值是一個(gè)字符串或者對象。
<router-link to="/home">首頁</router-link> <router-link to="{path: '/home'}">首頁</router-link>
- replace:設(shè)置 replace 屬性的化,路徑跳轉(zhuǎn)時(shí)將會直接替換掉舊路徑,舊路徑不會進(jìn)入歷史列表,回退頁面的話無法回退到舊頁面。
active-class
:設(shè)置激活 a 元素后應(yīng)用的 class 屬性名稱。默認(rèn)是router-link-active
。exact-active-class
:鏈接精準(zhǔn)激活時(shí),應(yīng)用于 a 元素的 class 屬性名稱。默認(rèn)是router-link-exact-active
。
<router-view>
組件:
<router-view>
:占位組件。路徑匹配時(shí)對應(yīng)組件的渲染容器。
嵌套路由:
通過 children 配置嵌套路由。
// src/router/index.js
import {createRouter, createWebHashHistory} from 'vue-router'import User from '../components/User.vue'
import UserProfile from '../components/UserProfile.vue'
import UserPosts from '@/components/UserPosts.vue'const router = createRouter({routes: [{path: '/user/:id', // 以 / 開頭的嵌套路徑將被視為根路徑component: User,// 1. 通過 children 配置嵌套路由children: [{// 當(dāng)路徑匹配到 /user/:id/profile,就會渲染 UserProfile 組件到 User 組件的 <router-view> 內(nèi)部path: 'profile', // // 在生成路由時(shí),主路由上的 path 會被自動添加到子路由之前,所以子路由上的 path 不用重新聲明主路由上的 path 了component: UserProfile,},{// 當(dāng)路徑匹配到 /user/:id/posts,就會渲染 UserPosts 組件到 User 組件的 <router-view> 內(nèi)部path: 'posts',component: UserPosts,},]},],history: createWebHashHistory(),
})export default router
// src/App.vue
<template><!-- 2. 頂層的 <router-view> 渲染頂層路由匹配的組件。User 組件將會被渲染到這個(gè)位置 --><router-view></router-view>
</template><script setup>
</script><style scoped>
</style>
// src/components/User.vue
<template><div>User:{{ $route.params.id }}</div><!-- 3. 一個(gè)被渲染的組件也可以包含自己嵌套的 <router-view>。UserProfile 和 UserPosts 組件將會被渲染到這個(gè)位置 --><router-view></router-view>
</template><script setup>
</script><style scoped>
</style>
動態(tài)路由:
路徑是動態(tài)的,路徑參數(shù)的部分在進(jìn)行路由匹配時(shí)可以變化,使用冒號標(biāo)記;當(dāng)匹配到一個(gè)路由時(shí),參數(shù)值會被設(shè)置到 $route.params
中。
// src/router/index.js
import {createRouter, createWebHashHistory} from 'vue-router'import User from '@/components/User.vue'const router = createRouter({routes: [// 1. 通過 :名稱 配置動態(tài)路由。路徑是動態(tài)的,路徑參數(shù)的部分在進(jìn)行路由匹配時(shí)是可以變化的{path: '/user/:id', component: User}],history: createWebHashHistory(),
})export default router
// src/App.vue
<template><!-- 2. 無論是 user/123 還是 user/456,都可以匹配得上 --><router-link to="/user/123">用戶123</router-link><router-link to="/user/456">用戶456</router-link><router-view></router-view>
</template><script setup>
</script><style scoped>
</style>
//src/components/User.vue
<template><!-- 3. 在 template 模板中獲取動態(tài)路由的值 --><div>User:{{ $route.params.id }}</div>
</template><script setup>
// 3. 在 Options API 中獲取動態(tài)路由的值
// this.$route.params.id// 3. 在 Composition API 中獲取動態(tài)路由的值。通過 useRoute() Hook 函數(shù)獲取
import { useRoute } from 'vue-router'
const route = useRoute()
console.log(route.params.id)
</script><style scoped>
</style>
可以在一個(gè)路由中設(shè)置多段路徑參數(shù),對應(yīng)的值都會設(shè)置到 $route.params
中。
/user/:username/post/:post_id
通過動態(tài)路由實(shí)現(xiàn) NotFound:
對于沒有匹配到的路由,通常會匹配到某個(gè)固定的頁面,例如 NotFound 頁面。可以編寫一個(gè)動態(tài)路由用于匹配所有的頁面。
// // src/router/index.js
import {createRouter, createWebHashHistory} from 'vue-router'import NotFound from '@/components/NotFound .vue'const router = createRouter({routes: [// 1. 如果匹配到任何一個(gè)不存在的路徑,那么就匹配 NotFound 組件。{path:'/:pathMatch(.*)', component: NotFound }],history: createWebHashHistory(),
})export default router
//src/components/NotFound .vue
<template><!-- 2. 獲取當(dāng)前的路徑參數(shù) --><div>NotFound:{{ $route.params.pathMatch }}</div>
</template><script setup>
</script><style scoped>
</style>
如果配置路由時(shí),在 /:pathMatch(.*)
后面再加一個(gè) *
,變成 {path:'/:pathMatch(.*)*', component: NotFound }
,那么在獲取路徑參數(shù)時(shí),會以 /
為分隔符將路徑參數(shù)解析為數(shù)組。
路由傳參:
- 可以通過動態(tài)路由的方式傳遞簡單參數(shù);在組件中通過
$route.params
的方法獲取。 - 也可以在通過代碼邏輯實(shí)現(xiàn)路徑跳轉(zhuǎn)時(shí),通過 query 傳遞參數(shù);在組件中通過
$route.query
獲取。const handleAboutNav = () => {router.push({path: '/about',// 1. 傳遞參數(shù)query: {name: 'Lee',age: 18,}}) }// 獲取參數(shù) import { useRoute } from 'vue-router' const route = useRoute() console.log(route.query.name)
路由懶加載:
// src/router/index.js
import {createRouter, createWebHashHistory} from 'vue-router'// 通過使用 import() 函數(shù)進(jìn)行路由懶加載。打包時(shí)會進(jìn)行分包處理,就可以在需要的時(shí)候再根據(jù)路徑下載對應(yīng)的組件代碼
const Home = () => import('../components/Home.vue')
const About = () => import('../components/About.vue')const router = createRouter({routes: [{path: '/', redirect: '/home'}, {path: '/home', component: Home},{path: '/about', component: About}],history: createWebHashHistory(),
})export default router
路由導(dǎo)航守衛(wèi):
Vue Router 提供的路由導(dǎo)航守衛(wèi)主要是通過跳轉(zhuǎn)或者取消的方式守衛(wèi)路由導(dǎo)航。
從一個(gè)路由跳轉(zhuǎn)到另一個(gè)路由,就叫路由導(dǎo)航。對中間跳轉(zhuǎn)的過程進(jìn)行攔截處理,就叫導(dǎo)航守衛(wèi)。
全局的導(dǎo)航守衛(wèi):
beforeEach()
:全局前置守衛(wèi)。跳轉(zhuǎn)到每個(gè)路由之前,beforeEach()
都會被觸發(fā)。beforeEach()
接收一個(gè)回調(diào)函數(shù)作為參數(shù)。
回調(diào)函數(shù)接收兩個(gè)參數(shù),to 表示即將進(jìn)入的路由對象,from 表示即將離開的路由對象。
回調(diào)函數(shù)的返回值如果是 false,取消當(dāng)前導(dǎo)航;如果不返回或者返回 undefined,進(jìn)行默認(rèn)導(dǎo)航;如果返回一個(gè)字符串類型或者對象類型的路徑地址,將會跳轉(zhuǎn)到這個(gè)指定的路徑。回調(diào)函數(shù)可選的第三個(gè)參數(shù)是 next。在 Vue2 中通過
next()
來決定如何進(jìn)行跳轉(zhuǎn);但在 Vue3 中是通過返回值來控制的。因此不再推薦使用next()
函數(shù)。router.beforeEach((to, from) => {if(to.path !== '/login') {return '/login'} })
afterEach()
:全局后置守衛(wèi)。不會改變導(dǎo)航本身。
組件內(nèi)的導(dǎo)航守衛(wèi):
在 Composition API 中,可以通過 onBeforeRouteUpdate 和 onBeforeRouteLeave 分別添加 update 和 leave 守衛(wèi)。
beforeRouteEnter()
:在進(jìn)入組件對應(yīng)的路由時(shí)觸發(fā)。此時(shí)組件實(shí)例還沒被創(chuàng)建,因?yàn)椴荒塬@取 this,可以通過回調(diào)函數(shù)的第三個(gè)參數(shù) next 來訪問組件實(shí)例。beforeRouteEnter (to, from, next) {next(instance=> {// 通過 instance 訪問組件實(shí)例}) }
beforeRouteUpdate()
:在路由改變,但是組件被復(fù)用時(shí)調(diào)用。此時(shí)組件已經(jīng)掛載好,導(dǎo)航守衛(wèi)可以獲取 this。例如對于一個(gè)帶有動態(tài)參數(shù)的路徑/users/:id
,在/users/1
和/users/2
之間跳轉(zhuǎn)的時(shí)候,由于會渲染同樣的UserDetails
組件,因此組件實(shí)例會被復(fù)用,這個(gè)鉤子就會在這個(gè)情況下被調(diào)用。beforeRouteLeave()
:在離開組件對應(yīng)的路由時(shí)觸發(fā)。此時(shí)導(dǎo)航守衛(wèi)可以獲取 this。
導(dǎo)航守衛(wèi)的解析流程:
- 導(dǎo)航被觸發(fā)。
- 在失活的組件里調(diào)用 beforeRouteLeave 守衛(wèi)。
- 調(diào)用全局的 beforeEach 守衛(wèi)。
- 在重用的組件里調(diào)用 beforeRouteUpdate 守衛(wèi)。
- 在路由配置里調(diào)用 beforeEnter。
- 解析異步路由組件。
- 在被激活的組件里調(diào)用 beforeRouteEnter。
- 調(diào)用全局的 beforeResolve 守衛(wèi)。
- 導(dǎo)航被確認(rèn)。
- 調(diào)用全局的 afterEach 鉤子。
- 觸發(fā) DOM 更新。
- 調(diào)用 beforeRouteEnter 守衛(wèi)中傳給 next 的回調(diào)函數(shù),創(chuàng)建好的組件實(shí)例會作為回調(diào)函數(shù)的參數(shù)傳入。