使用
1安裝
npm install vue-router
2新建router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//路由規(guī)則
const routes = [
{
path: './home',
component: () => import('xx/home.vue')
},
{
path: './about',
component: () => import('xx/about.vue')
}
]
//實(shí)例化路由對(duì)象
const router = new VueRouter({
routes // (縮寫) 相當(dāng)于 routes: routes
})
export default router
3創(chuàng)建和掛載根實(shí)例
在main.js:
const app = new Vue({
router,
render: h => h(App)
}).$mount('#app')
通過注入路由器,我們可以在任何組件內(nèi)通過this.$router 訪問路由器,也可以通過this.$route訪問當(dāng)前路由。
說明:
--router:路由器對(duì)象,通過new Vue()暴露出來的實(shí)例對(duì)象,它上面有一些用來操作路由切換的方法(編程式導(dǎo)航的方法)通過this.$router去使用
--route:路由對(duì)象,包含當(dāng)前匹配的路由的信息,通過this.$route去使用
// http://localhost:8080/#/topicShare?topic_id=1915
this.$route.path// "/topicShare"
this.$route.query// object, topic_id:1915
this.$route.params// object
this.$route.fullPath// "/topicShare?topic_id=1915"
this.$route.name// ""
this.$route.meta// object
this.$route.matched// array
動(dòng)態(tài)路由匹配
const router = new VueRouter({
routes: [
// 動(dòng)態(tài)路徑參數(shù) 以冒號(hào)開頭
{
path: '/user/:id',
component: () => { 'xxx/User.vue' }
}
]
})
/user/foo 和 /user/bar 都將映射到相同的路由,通過this.$route.params.id獲取當(dāng)前路由id
響應(yīng)路由參數(shù)的變化
當(dāng)使用動(dòng)態(tài)路由參數(shù)時(shí),例如從 /user/foo 導(dǎo)航到 /user/bar,原來的組件實(shí)例會(huì)被復(fù)用,組件的生命周期鉤子不會(huì)再被調(diào)用。
復(fù)用組件時(shí),想對(duì)路由參數(shù)的變化作出響應(yīng)的話,你可以簡(jiǎn)單地 watch (監(jiān)測(cè)變化) $route 對(duì)象:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// 對(duì)路由變化作出響應(yīng)...
}
}
}
或者使用 2.2 中引入的 beforeRouteUpdate 導(dǎo)航守衛(wèi):
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
有時(shí)候,同一個(gè)路徑可以匹配多個(gè)路由,此時(shí),匹配的優(yōu)先級(jí)就按照路由的定義順序:誰先定義的,誰的優(yōu)先級(jí)就最高。
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: () => import('xx/User.vue'),
children: [
{
// 當(dāng) /user/:id/profile 匹配成功,
// UserProfile 會(huì)被渲染在 User 的 <router-view> 中
path: 'profile',
component: () => import('xx/UserProfile.vue')
},
{
// 當(dāng) /user/:id/posts 匹配成功
// UserPosts 會(huì)被渲染在 User 的 <router-view> 中
path: 'posts',
component: () => import( 'xx/UserPosts.vue')
},
{
// 當(dāng) /user/:id 匹配成功,
// UserHome 會(huì)被渲染在 User 的 <router-view> 中
path: '',
component: () => import('xx/UserHome.vue')
}
]
}
]
})
編程式導(dǎo)航
| 聲明式導(dǎo)航 | 編程式導(dǎo)航 |
|---|---|
| <router-link :to="..."> | this.$router.push(...) |
| <router-link :to="..." replace> | this.$router.replace(...) |
| wu | this.$routergo(1) |
// 字符串
this.$router.push('home')
// 對(duì)象
this.$router.push({ path: 'home' })
// 命名的路由
this.$router.push({ name: 'user', params: { userId: '123' }})
// 帶查詢參數(shù),變成 /register?plan=private
this.$router.push({ path: 'register', query: { plan: 'private' }})
如果提供了 path,params 會(huì)被忽略。
const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 這里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user
this.$router.replace()//替換掉當(dāng)前的 history 記錄,不會(huì)向 history 添加新記錄
this.$router.go(n)//在 history 記錄中向前或者后退多少步
命名路由---name
const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user',
component: () => import('xx/User.vue')
}
]
})
要鏈接到一個(gè)命名路由,可以給 router-link 的 to 屬性傳一個(gè)對(duì)象:
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
這跟代碼調(diào)用 router.push() 是一回事:
this.$router.push({ name: 'user', params: { userId: 123 }})
命名視圖---同級(jí)展示多個(gè)視圖
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
如果 router-view 沒有設(shè)置名字,那么默認(rèn)為 default
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
重定向---redirect
const router = new VueRouter({
routes: [
{ path: '/a', redirect: '/b' }
]
})
模式---mode
vue-router 默認(rèn) hash 模式,有#
const router = new VueRouter({
mode: 'history',
routes: [...]
})
路由元信息---meta
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
meta: { requiresAuth: true }
}
]
})
eg:在全局導(dǎo)航守衛(wèi)中檢查元字段
router.beforeEach((to, from, next) => {
//to:即將要跳轉(zhuǎn)的路由;matched:array; array.some()檢測(cè)數(shù)組中的元素是否滿足指定條件
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 確保一定要調(diào)用 next()
}
})
滾動(dòng)行為
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滾動(dòng)到哪個(gè)的位置
return { x: 0, y: 0 }
}
})
路由懶加載
const router = new VueRouter({
routes: [
{ path: '/foo', component: () => import('xx/Foo.vue') }
]
})
<router-link>的props
1to
<!-- 字符串 -->
<router-link to="home">Home</router-link>
<!-- 渲染結(jié)果 -->
<a href="home">Home</a>
<!-- 命名的路由 -->
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
<!-- 帶查詢參數(shù),下面的結(jié)果為 /register?plan=private -->
<router-link :to="{ path: 'register', query: { plan: 'private' }}"
>Register</router-link
>
2replace
設(shè)置 replace 屬性的話,當(dāng)點(diǎn)擊時(shí),會(huì)調(diào)用 router.replace() 而不是 router.push(),于是導(dǎo)航后不會(huì)留下 history 記錄。
<router-link :to="{ path: '/abc'}" replace></router-link>
3append
設(shè)置 append 屬性后,則在當(dāng)前 (相對(duì)) 路徑前添加基路徑。例如,我們從 /a 導(dǎo)航到一個(gè)相對(duì)路徑 b,如果沒有配置 append,則路徑為 /b,如果配了,則為 /a/b
<router-link :to="{ path: 'relative/path'}" append></router-link>
4tag
想要 <router-link> 渲染成某種標(biāo)簽,例如 <li>。 可以使用 tag prop 類指定何種標(biāo)簽,同樣它還是會(huì)監(jiān)聽點(diǎn)擊,觸發(fā)導(dǎo)航。
<router-link to="/foo" tag="li">foo</router-link>
<!-- 渲染結(jié)果 -->
<li>foo</li>
5active-class
設(shè)置鏈接激活時(shí)使用的 CSS 類名
6exact
精確匹配模式
<router-view> 的Props
name命名視圖
<template>
<div>
<keep-alive :exclude="keepAliveExclude">
<router-view />
</keep-alive>
</div>
</template>