Vue-router官網(wǎng)
由vue-router模塊控制,需要額外安裝依賴。參考官網(wǎng)
npm install vue-router --save
組成
- router-link:路由鏈接,跳轉(zhuǎn)至路由視圖,展示指定路由組件信息
- router-view:路由視圖,展示路由組件信息
- route:路由信息
- router:路由對象
router-link
路由跳轉(zhuǎn),類似a標簽,路由跳轉(zhuǎn)作用
<router-link to="" />
router-view
路由視圖,用于其他組件在該視圖位置顯示。
<router-view name="name" />
<!-- 可以指定視圖名,在路由跳轉(zhuǎn)時可通過視圖名指定視圖位置跳轉(zhuǎn)路由 -->
route
{
path:'/url',
name:'name',
components:{ // one,two會綁定對應(yīng)名稱的路由視圖上<router-view name='name'/>
default: ComponentZero,
one:ComponentOne,
two:ComponentTwo,
},
meta: { transition: 'slide-right' }, // 路由元信息,可以通過router.meta獲取指定元信息
component:ComponentZero, //在默認路由視圖上跳轉(zhuǎn)
redirect:'', // 重定向,也可詳細描述route信息{path:'url'}
children:[ // 嵌套路由
{
path:'/url1', // 即/url/url1/的訪問
component:ComponentOne,
},
{
path:'/url2', // 即/url/url2/的訪問
component:ComponentTwo,
}
],
beforeEnter:(to, from) => { // 路由守衛(wèi),獨享
// reject the navigation
return false
},
}
router
{
history:createWebHashHistory(), // history模式,hash式和非hash式
routes:routes,// 綁定路由集
strict: true, // 嚴格區(qū)分大小寫,也可在單個路由配置
sensitive: true, // 不區(qū)分大小寫,也可在單個路由配置
scrollBehavior (to, from, savedPosition) { //滾動行為
// return 期望滾動到哪個的位置
},
}
匹配規(guī)則
- 自定義正則
- 可重復(fù)參數(shù)
- 大小寫敏感控制
- 可選參數(shù)
const routes = [
// 匹配 /o/3549
{ path: '/o/:orderId' },
// 匹配 /p/books
{ path: '/p/:productName' },
// /:orderId -> 僅匹配數(shù)字
{ path: '/:orderId(\\d+)' },
// /:productName -> 匹配其他任何內(nèi)容
{ path: '/:productName' },
// /:chapters -> 匹配 /one, /one/two, /one/two/three, 等,至少有一個參數(shù),否則異常
{ path: '/:chapters+' },
// /:chapters -> 匹配 /, /one, /one/two, /one/two/three, 等
{ path: '/:chapters*' },
// 匹配 /, /1, /1/2, 等
{ path: '/:chapters(\\d+)*' },
// 將匹配 /users/posva 而非:
// - /users/posva/ 當 strict: true
// - /Users/posva 當 sensitive: true
{ path: '/users/:id', sensitive: true },
// 將匹配 /users, /Users, 以及 /users/42 而非 /users/ 或 /users/42/
{ path: '/users/:id?' },
// 匹配 /users 和 /users/posva
{ path: '/users/:userId?' },
// 匹配 /users 和 /users/42
{ path: '/users/:userId(\\d+)?' },
]
配置&使用
- 定義路由組件component
- 定義路由集routes
- 創(chuàng)建路由實例router
- 選擇history模式:hash(路徑帶#)和H5模式
- 掛載路由到app根
// 1. 定義路由組件.
// 也可以從其他文件導(dǎo)入
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
// 2. 定義一些路由
// 每個路由都需要映射到一個組件。
// 我們后面再討論嵌套路由。
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
// 3. 創(chuàng)建路由實例并傳遞 `routes` 配置
// 你可以在這里輸入更多的配置,但我們在這里
// 暫時保持簡單
// VueRouter : import { createRouter, createWebHistory } from 'vue-router'
const router = VueRouter.createRouter({
// 4. 內(nèi)部提供了 history 模式的實現(xiàn)。
// hash 模式 createWebHashHistory()
// H5模式 createWebHistory();
history: VueRouter.createWebHashHistory(),
routes, // `routes: routes` 的縮寫
})
// 5. 創(chuàng)建并掛載根實例
const app = Vue.createApp({})
//確保 _use_ 路由實例使
//整個應(yīng)用支持路由。
app.use(router)
app.mount('#app')
動態(tài)路由
- 路徑參數(shù)用
:
冒號修飾的, - 參數(shù)支持正則表達式匹配,
- 代表可以傳遞動態(tài)數(shù)據(jù)到組件中,并且組件也可以讀取參數(shù)。
- 通過
$router.param.var-name
接收var-name
變量值 - 支持多個參數(shù)綁定和接收
// 這些都會傳遞給 `createRouter`
const routes = [
// 動態(tài)字段以冒號開始
{ path: '/users/:id', component: User },
]
const User = {
template: '<div>User {{ $route.params.id }}</div>',
}
嵌套路由
即由children定義的子路由集。
const routes = [
{
path: '/user/:id',
name: 'user-parent',
component: User,
children: [{ path: '', name: 'user', component: UserHome }],
},
]
導(dǎo)航
- router-link元素方式
- router.push編程方式
- 替換方式:不會向history添加記錄
// <router-link :to="...">
// 字符串路徑
router.push('/users/eduardo')
// 帶有路徑的對象
router.push({ path: '/users/eduardo' })
// 命名的路由,并加上參數(shù),讓路由建立 url
router.push({ name: 'user', params: { username: 'eduardo' } })
// 帶查詢參數(shù),結(jié)果是 /register?plan=private
router.push({ path: '/register', query: { plan: 'private' } })
// 帶 hash,結(jié)果是 /about#team
router.push({ path: '/about', hash: '#team' })
const username = 'eduardo'
// 我們可以手動建立 url,但我們必須自己處理編碼
router.push(`/user/${username}`) // -> /user/eduardo
// 同樣
router.push({ path: `/user/${username}` }) // -> /user/eduardo
// 如果可能的話,使用 `name` 和 `params` 從自動 URL 編碼中獲益
router.push({ name: 'user', params: { username } }) // -> /user/eduardo
// `params` 不能與 `path` 一起使用
router.push({ path: '/user', params: { username } }) // -> /user
// <router-link :to="..." replace>
router.push({ path: '/home', replace: true })
// 相當于
router.replace({ path: '/home' })
命名路由
即配置name屬性的路由,導(dǎo)航時可綁定name屬性。
const routes = [
{
path: '/user/:username',
name: 'user',
component: User,
},
]
// <router-link :to="{ name: 'user', params: { username: 'erina' }}"> User </router-link>
router.push({ name: 'user', params: { username: 'erina' } })
// 導(dǎo)航至 /user/erina
命名視圖
即帶有name屬性路由視圖,在路由導(dǎo)航時可通過命名在指定視圖上導(dǎo)航
<router-view class="view left-sidebar" name="LeftSidebar"></router-view>
<router-view class="view main-content"></router-view>
<router-view class="view right-sidebar" name="RightSidebar"></router-view>
routes: [
{
path: '/',
components: {
default: Home,
// LeftSidebar: LeftSidebar 的縮寫
LeftSidebar,
// 它們與 `<router-view>` 上的 `name` 屬性匹配
RightSidebar,
},
},
],
重定向和別名
- redirect重定向,分為絕對和相對
- alias 別名,可以單個,也可以多個
const routes = [
{
// 將總是把/users/123/posts重定向到/users/123/profile。
path: '/users/:id/posts',
redirect: to => {
// 該函數(shù)接收目標路由作為參數(shù)
// 相對位置不以`/`開頭
// 或 { path: 'profile'}
return 'profile'
},
},
{ path: '/home', redirect: { name: 'homepage' } }, // 絕對重定向
{ path: '/user', component: Homepage, alias: ['/people', 'list'] }
]
路由組件傳參
- 若組件需要接收props參數(shù)值,則路由配置時需要聲明props為true
- 對于命名視圖的路由,則需要針對每個命名視圖都要聲明props配置
const routes = [
{ path: '/user/:id', component: User, props: true },
{
path: '/users/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
歷史模式
- hash模式:createWebHashHistory(),路徑帶
#
修飾符 - H5模式:createWebHistory(),推薦使用
路由守衛(wèi)
- 全局守衛(wèi)
- beforeEach 路由跳轉(zhuǎn)前置處理處理
- beforeResolve 路由解析,導(dǎo)航被確認之前,同時在所有組件內(nèi)守衛(wèi)和異步路由組件被解析之后調(diào)用
- afterEach 路由跳轉(zhuǎn)后置處理,可以分析,修改頁面標題等
- 獨享守衛(wèi)
- beforeEnter 獨享路由守衛(wèi),在配置路由時綁定,只在進入對應(yīng)路由時觸發(fā)
- 組件內(nèi)守衛(wèi)
- beforeRouteEnter 組件創(chuàng)建前調(diào)用,內(nèi)部不能使用this
- beforeRouteUpdate 組件更新時調(diào)用,一般對應(yīng)動態(tài)路由時
- beforeRouteLeave 離開組件時調(diào)用
const UserDetails = {
template: `...`,
beforeRouteEnter(to, from) {
// 在渲染該組件的對應(yīng)路由被驗證前調(diào)用
// 不能獲取組件實例 `this` !
// 因為當守衛(wèi)執(zhí)行時,組件實例還沒被創(chuàng)建!
},
beforeRouteUpdate(to, from) {
// 在當前路由改變,但是該組件被復(fù)用時調(diào)用
// 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 `/users/:id`,在 `/users/1` 和 `/users/2` 之間跳轉(zhuǎn)的時候,
// 由于會渲染同樣的 `UserDetails` 組件,因此組件實例會被復(fù)用。而這個鉤子就會在這個情況下被調(diào)用。
// 因為在這種情況發(fā)生的時候,組件已經(jīng)掛載好了,導(dǎo)航守衛(wèi)可以訪問組件實例 `this`
},
beforeRouteLeave(to, from) {
// 在導(dǎo)航離開渲染該組件的對應(yīng)路由時調(diào)用
// 與 `beforeRouteUpdate` 一樣,它可以訪問組件實例 `this`
},
}
路由懶加載
即僅在訪問時初始化組件。文章來源:http://www.zghlxwxcb.cn/news/detail-420831.html
{path:'url',component:() => import('./views/UserDetails.vue')}
導(dǎo)航故障
- 等待導(dǎo)航結(jié)果
- 檢測導(dǎo)航故障
- 鑒別導(dǎo)航故障
- aborted:導(dǎo)航守衛(wèi)返回false被阻止
- cancelled:導(dǎo)航未完成之前又有新導(dǎo)航,如等待導(dǎo)航的過程中有調(diào)用了路由導(dǎo)航
- duplicated:已在目標位置,導(dǎo)航被阻止
- 檢測重定向
// 使用await同步修飾符等待導(dǎo)航結(jié)果
const navigationResult = await router.push('/my-profile')
import { NavigationFailureType, isNavigationFailure } from 'vue-router'
if(isNavigationFailure(failure, NavigationFailureType.aborted)){
// 檢測導(dǎo)航故障類型
}
動態(tài)路由
- createRouter 創(chuàng)建路由實例
- addRouter 未路由實例添加新動態(tài)路由及嵌套路由
router.addRoute({ name: 'admin', path: '/admin', component: Admin })
router.addRoute('admin', { path: 'settings', component: AdminSettings })
- removeRoute 刪除路由
- 通過命名沖突覆蓋方式刪除舊路由
- 通過addRouter的回調(diào)方式刪除
- 通過路由別名刪除
// 這將會刪除之前已經(jīng)添加的路由,因為他們具有相同的名字且名字必須是唯一的
router.addRoute({ path: '/other', name: 'about', component: Other })
const removeRoute = router.addRoute(routeRecord)
removeRoute() // 刪除路由如果存在的話
// 刪除路由
router.removeRoute('about')
- hasRoute 查看路由是否存在
- getRoute 獲取路由
擴展RouterLink
<template>
<a v-if="isExternalLink" v-bind="$attrs" :href="to" target="_blank">
<slot />
</a>
<router-link
v-else
v-bind="$props"
custom
v-slot="{ isActive, href, navigate }"
>
<a
v-bind="$attrs"
:href="href"
@click="navigate"
:class="isActive ? activeClass : inactiveClass"
>
<slot />
</a>
</router-link>
</template>
<script>
import { RouterLink } from 'vue-router'
export default {
name: 'AppLink',
inheritAttrs: false,
props: {
// 如果使用 TypeScript,請?zhí)砑?@ts-ignore
...RouterLink.props,
inactiveClass: String,
},
computed: {
isExternalLink() {
return typeof this.to === 'string' && this.to.startsWith('http')
},
},
}
</script>
如果使用渲染函數(shù)或創(chuàng)建 computed 屬性,你可以使用 Composition API 中的 useLink文章來源地址http://www.zghlxwxcb.cn/news/detail-420831.html
import { RouterLink, useLink } from 'vue-router'
export default {
name: 'AppLink',
props: {
// 如果使用 TypeScript,請?zhí)砑?@ts-ignore
...RouterLink.props,
inactiveClass: String,
},
setup(props) {
// `props` 包含 `to` 和任何其他可以傳遞給 <router-link> 的 prop
const { navigate, href, route, isActive, isExactActive } = useLink(props)
// profit!
return { isExternalLink }
},
}
<template>
<AppLink
v-bind="$attrs"
class="inline-flex items-center px-1 pt-1 border-b-2 border-transparent text-sm font-medium leading-5 text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700 focus:border-gray-300 transition duration-150 ease-in-out"
active-class="border-indigo-500 text-gray-900 focus:border-indigo-700"
inactive-class="text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:text-gray-700 focus:border-gray-300"
>
<slot />
</AppLink>
</template>
到了這里,關(guān)于【Vue】Vue-route路由的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!