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

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