1. 程式人生 > 其它 >vue vue-router實現路由攔截功能

vue vue-router實現路由攔截功能

技術標籤:學習工作vuejsnodejsjavascript

vue vue-router實現路由攔截功能

1、目錄結構

在這裡插入圖片描述

2、設定路由攔截、

路由配置如下,在這裡自定義了一個物件的引數meta: {authRequired: true}來標記哪些路由是需要登入驗證的,導航被觸發的時候只要判斷是否目標路由中是否有meta這個物件,且meta包含authRequired屬性,其值為true。這裡訪問帶有meta物件的路由是被攔截的。
 {
        path: '/config',
        name: 'config',
        meta: { 
          requireAuth:
true }, component: Config }, { path: '/about1', name: 'about1', meta: { requireAuth: true }, component: About1 }, { path: '/app', name: 'app', component: App }, { path:
'/application', name: 'application', meta: { requireAuth: true }, component: Application },

3、全域性函式beforeEach

main.js通過router.beforeEach全域性函式,每次路由跳轉都會出發函數判斷是否有登入資訊

router.beforeEach((to, from, next) => {
  if (to.matched.some(res => res.meta.
requireAuth)) { // 驗證是否需要登陸 var id=window.sessionStorage.getItem('userId'); console.log(id) if (id) { // 查詢本地儲存資訊是否已經登陸 next(); } else { next({ path: '/login', // 未登入則跳轉至login頁面 redirect: '/main2' // 登陸成功後回到當前頁面,這裡傳值給login頁面,to.fullPath為當前點選的頁面 }); } } else { next(); } }

4、在登陸介面利用sessionStorage將資訊存入到全域性變數

  login() {

                axios.get('http://192.168.56.1:8081/sel/1', {// /gr/goods/add
                    userid: this.loginForm.userid,
                    pwd: this.loginForm.pwd,
                    
                }).then((res) => {
                    
                    console.log(res);
                    console.log(res.data.msg);
                    this.$store.commit('setUserId',this.loginForm.userid);
                    this.$store.commit('setUserPwd',this.loginForm.pwd);
                    console.log(this.loginForm.userid);
                    console.log(this.loginForm.userpwd);
                    console.log("列印的id為:"+sessionStorage.getItem('userId'));
                    console.log("列印的pwd為:"+sessionStorage.getItem('userPwd'));

注意:

之後每次進行路由的時候都會判斷登入資訊,在登出的時候呼叫函式,;利用sessionStroage.clear()將全域性資訊清楚。防止登出之後路由攔截失效