一.watch監聽$route($router的對象)
// 監聽,當路由發生變化的時候執行
watch:{$route(to,from){console.log(to.path);}
},
===========================================================
// 監聽,當路由發生變化的時候執行
watch: {$route: {handler: function(val, oldVal){console.log(val);},// 深度觀察監聽deep: true}
},
===========================================================
// 監聽,當路由發生變化的時候執行
watch: {'$route':'getPath'
},
methods: {getPath(){console.log(this.$route.path);}
}
二. vue-router 的鉤子函數(寫在與methods同級的地方或者router中)
beforeRouteEnter (to, from, next) {// 在渲染該組件的對應路由被 confirm 前調用// 不!能!獲取組件實例 `this`// 因為當鉤子執行前,組件實例還沒被創建
},
===========================================================
beforeRouteUpdate (to, from, next) {// 在當前路由改變,但是該組件被復用時調用// 舉例來說,對于一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,// 由于會渲染同樣的 Foo 組件,因此組件實例會被復用。而這個鉤子就會在這個情況下被調用。// 可以訪問組件實例 `this`
},
===========================================================
beforeRouteLeave (to, from, next) {// 導航離開該組件的對應路由時調用// 可以訪問組件實例 `this`
},
完整的導航解析流程
- 導航被觸發。
- 在失活的組件里調用 beforeRouteLeave 守衛。
- 調用全局的 beforeEach 守衛。
- 在重用的組件里調用 beforeRouteUpdate 守衛 (2.2+)。
- 在路由配置里調用 beforeEnter。
- 解析異步路由組件。
- 在被激活的組件里調用 beforeRouteEnter。
- 調用全局的 beforeResolve 守衛 (2.5+)。
- 導航被確認。
- 調用全局的 afterEach 鉤子。
- 觸發 DOM 更新。
- 調用 beforeRouteEnter 守衛中傳給 next 的回調函數,創建好的組件實例會作為回調函數的參數傳入。
三. 路由守衛
import Vue from "vue";
import VueRouter from "vue-router";
import store from '@/store'
Vue.use(VueRouter);const routes = [***]const router = new VueRouter({routes
});// 設置路由守衛,在進頁面之前,判斷有token,才進入頁面,否則返回登錄頁面
router.beforeEach((to, from, next) => {// 判斷要去的路由有沒有 noRequireToken// to.matched.some(r => r.meta.noRequireToken) or to.meta.noRequireTokenif (to.matched.some(r => !r.meta.noRequireToken)) {let token = store.getters.getTokenconsole.log("token:", token,to.fullPath)if (token) {next(); //有token,進行request請求,后臺還會驗證token} else {next({name: "Login", // 使用params參數不會消失,meta刷新后消失;params必須和query一起用?// path:"/login",// 將剛剛要去的路由path(卻無權限)作為參數,方便登錄成功后直接跳轉到該路由,這要進一步在登陸頁面判斷query: { redirect: to.fullPath },// params: { redirect: to.fullPath },// meta: { redirect: to.fullPath },});}} else {next(); //如果無需token,那么隨它去吧}
});export default router;
組件獨享守衛
const router = new VueRouter({routes: [{path: '/foo',component: Foo,beforeEnter: (to, from, next) => {// ...}}]
})
官網介紹 vue-router