[toc]
##
路由守衛函數會幫助我們監控整個路由的切換
,我們必須調用`next()`才能進入路由的下一個階段
## router上的三個路由守衛函數
`router`是`new Router()`出來的示例
### beforeEach
```
router.beforeEach((to, from, next) => {
console.log('beforeEach invoked');
if(to.fullPath.startsWith('/app')){
//調用next才會進行跳轉
//不要跳轉到自己,會infinite loop
// next('/login');
next('/login');
//不僅可以寫字符串,也可以寫一個object,傳入的和router-link上聲明的東西是一樣的
next({path:'/login',replace:true})
}else{
next();
}
next();
});
```
### beforeResolve
beforeEach->beforeEnter->beforeRouteEnter都觸發后才會觸發
```
router.beforeResolve((to, from, next) => {
console.log('beforeResolve invoked');
next();
});
```
### afterEach
```
router.afterEach((to, from) => {
//無需next,路由已經跳轉
console.log('afterEach invoked');
});
```
## beforeEnter:每條路由進入前各自的路由守衛函數
會在router.beforeEach之后,router.beforeResolve之前調用
```
, beforeEnter(to, from, next) {
console.log('app route before enter');
next();
}
```
## 組件內部的路由守衛函數
已確定要進入 組件所在路由 時觸發的路由守衛函數
### beforeRouteEnte
```
//在route的beforeEnter觸發后才會觸發beforeRouteEnter
// enter和update不會同時觸發!!
beforeRouteEnter(to,from,next){
console.log('todo before enter');
},
```
需要注意的是路由守衛函數中并**不能**直接拿到組件的**this**
想要獲取組件的實例需要,在路由守衛函數中調用next時使用函數傳參
```
//vm為todo被創建好后的this對象
//id為通過路由配置的props屬性注入
next(vm=>{
console.log('after enter this.id is',vm.id)
})
```
### beforeRouteUpdate
同一個組件在不同的路由下面都是由這個組件顯示的時候才會觸發
>case1:如果是同一路由下
>
比如說動態路由 /app/:id 動態路由參數不同時會觸發
注意 如果從/app/3 切換到 /other 再切換到/app/4 是不會觸發的
>case2:使用命名視圖
```
beforeRouteUpdate(to,from,next){
console.log('todo before update');
next();
},
```
>[danger] 需要注意的是組件的update和enter路由守衛函數一定不會同時觸發
>
### beforeRouteLeave
切換路由時最先觸發的守衛函數,后面是beforeEach
一般用于一不小心要離開時點擊確認
```
beforeRouteLeave(to,from,next){
console.log('todo before leave');
next();
},
```
- 空白目錄
- vue-cli
- runtime-only
- Vue對比React
- 組件與實例
- data-binding
- computed的set和get
- scoped
- 事件
- 自定義指令
- 插件
- keep-alive
- $nextTick與生命周期
- 路由
- Vue.use(Router)
- this.$router編程式導航
- this.$route
- new Router
- routes
- mode
- linkClass
- scrollBehavior
- query
- fallback
- base
- router-view
- router-link
- 路由守衛
- 左右切換
- 滾動
- FAQ
- vuex
- 適用
- new Vuex.Store
- state
- mutations
- getters
- actions
- strict
- plugins
- modules
- namespace
- this.$store
- commit
- dispatch
- mapXX
- eventBus
- Vue工程相關
- 引用路徑的簡化
- css-module
- vue-loader
- 異步加載
- 支持jsx
- 讓webpack支持對vuex的熱替換
- .eslintrc