- 配置路由模式(三種模式)
const router = new VueRouter({//創(chuàng)建路由實例
mode: 'history',//模式
routes
})
· 默認(rèn)hash: 使用URL hash值作為路由,支持所有瀏覽器
· history: 依賴HTML5 History API和服務(wù)器配置
· abstract:支持所有 JavaScript 運行環(huán)境,如 Node.js 服務(wù)器端。如果發(fā)現(xiàn)沒有瀏覽器的 API,路由會自動強(qiáng)制進(jìn)入這個模式。
默認(rèn)是hash,路由通過“#”隔開,但是如果工程中有錨鏈接或者路由中有hash值,原先的“#”就會對頁面跳轉(zhuǎn)產(chǎn)生影響;所以就需要使用history模式;
采用history模式有一個缺點就是會在當(dāng)前路由下刷新會找不到頁面(如下圖所示)

需要在webpack.config.js中設(shè)置,這樣在當(dāng)前路由刷新就不會找不到頁面了。
devServer: {
historyApiFallback: true
}
- 路由導(dǎo)航鉤子
2.1 全局鉤子const router = new VueRouter({ ... })
//導(dǎo)航開始時
router.beforeEach((to, from, next) => {
// to 目標(biāo)路由對象
// from 即將進(jìn)入的路由對象
//next Function必須調(diào)用
// next() 進(jìn)行下一個鉤子,知道全部鉤子執(zhí)行完
//next(false) 中斷當(dāng)前
//next('/') or next({path:'/'})
})
//導(dǎo)航結(jié)束時
router.afterEach((to, from) => {
//afterEach沒有next,不能改變導(dǎo)航
})
```
2.2 某個路由的鉤子
你可以在路由配置上直接定義 beforeEnter , afterEnter鉤子:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
},
afterEnter: (to, from) => {
// ...
}
}
]
})
2.3 組件內(nèi)鉤子
在組件內(nèi)直接定義以下鉤子
beforeRouteEnter
beforeRouteUpdate (2.2 新增)
beforeRouteLeave
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
// 在渲染該組件的對應(yīng)路由被 confirm 前調(diào)用
// 不!能!獲取組件實例 `this`
// 因為當(dāng)鉤子執(zhí)行前,組件實例還沒被創(chuàng)建
},
beforeRouteUpdate (to, from, next) {
// 在當(dāng)前路由改變,但是改組件被復(fù)用時調(diào)用
// 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時候,
// 由于會渲染同樣的 Foo 組件,因此組件實例會被復(fù)用。而這個鉤子就會在這個情況下被調(diào)用。
// 可以訪問組件實例 `this`
},
beforeRouteLeave (to, from, next) {
// 導(dǎo)航離開該組件的對應(yīng)路由時調(diào)用
// 可以訪問組件實例 `this`
}
}
beforeRouteEnter 鉤子 不能 訪問 this,因為鉤子在導(dǎo)航確認(rèn)前被調(diào)用,因此即將登場的新組件還沒被創(chuàng)建。