最原始沒有任何干擾的路由攔截 其他資料

import Vue from 'vue'; import Router from 'vue-router'; import home from './home'; Vue.use(Router); const RouterModel = new Router({ routes: [...home] }); // router.beforeEach RouterModel.beforeEach((to, from, next) => { next(); }); export default RouterModel;
有條件的路由判斷
router.beforeEach(function (to,from,next) { //console.log(to,from,next) //需求登錄判斷 if(to.meta.auth){ /*不為空*/ if(sessionStorage.getItem('user')){ next(); }else{ next('/login?redirect='+to.fullPath) //這里與上面的相對應,此處也可以寫成 /*** next({ path: '/login', query: { redirect: to.fullPath } })***/ //上面為另外一種寫法 } } else{ next(); } })
注意要在main.js中引入並注冊


全局前置守衛
你可以使用 router.beforeEach 注冊一個全局前置守衛:
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
當一個導航觸發時,全局前置守衛按照創建順序調用。守衛是異步解析執行,此時導航在所有守衛 resolve 完之前一直處於 等待中。
每個守衛方法接收三個參數:
-
to: Route: 即將要進入的目標 路由對象 -
from: Route: 當前導航正要離開的路由 -
next: Function: 一定要調用該方法來 resolve 這個鈎子。執行效果依賴next方法的調用參數。-
next(): 進行管道中的下一個鈎子。如果全部鈎子執行完了,則導航的狀態就是 confirmed (確認的)。 -
next(false): 中斷當前的導航。如果瀏覽器的 URL 改變了 (可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到from路由對應的地址。 -
next('/')或者next({ path: '/' }): 跳轉到一個不同的地址。當前的導航被中斷,然后進行一個新的導航。你可以向next傳遞任意位置對象,且允許設置諸如replace: true、name: 'home'之類的選項以及任何用在router-link的toprop 或router.push中的選項。 -
next(error): (2.4.0+) 如果傳入next的參數是一個Error實例,則導航會被終止且該錯誤會被傳遞給router.onError()注冊過的回調。
-
確保要調用 next 方法,否則鈎子就不會被 resolved。
