1. 程式人生 > >vue2.0 實現導航守衛 --- 齊梟飛 前端開發攻城獅(路由守衛) 使用vue-router+vuex進行導航守衛

vue2.0 實現導航守衛 --- 齊梟飛 前端開發攻城獅(路由守衛) 使用vue-router+vuex進行導航守衛

路由跳轉前做一些驗證,比如登入驗證,是網站中的普遍需求。

對此,vue-route 提供的 beforeRouteUpdate 可以方便地實現導航守衛(navigation-guards)。

導航守衛(navigation-guards)這個名字,聽起來怪怪的

全域性守衛 你可以使用 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(error): (2.4.0+) 如果傳入 next 的引數是一個 Error 例項,則導航會被終止且該錯誤會被傳遞給 router.onError() 註冊過的回撥。 確保要呼叫 next 方法,否則鉤子就不會被 resolved。

想要實現登入後才能進入主頁等其他頁面,不然都會跳轉到登入頁。但是Vuex有個不夠完美的地方,一旦重新整理頁面就會沒了,所以還要用到localStorage。

一、router.js:

import Vue from ‘vue’ import Router from ‘vue-router’ import HelloWorld from ‘@/components/HelloWorld’ import store from ‘…/store/index’

Vue.use(Router); // 懶載入元件 const login = () => import(‘Components/common/login/index.vue’); const loading = () => import(‘Components/common/loading/index.vue’); const home = () => import(‘Pages/home/home.vue’); const user = () => import(‘Pages/userManage/index.vue’); const addUser = () => import(‘Pages/userManage/add/index.vue’); const editUser = () => import(‘Pages/userManage/edit/index.vue’); const menu = () => import(‘Pages/menuManage/index.vue’); const umbrella = () => import(‘Pages/umbrellaManage/index.vue’); const location = () => import(‘Pages/locationManage/index.vue’); const order = () => import(‘Pages/orderManage/index.vue’);

const test = () => import(‘Pages/test.vue’);

const routes = [ // 登入頁面 { path: ‘/login’, name: “login”, component: login, meta: { requiresAuth: false } },

{ path: ‘*’, redirect: ‘/home’, name: ‘HelloWorld’, component: HelloWorld, children: [ // 測試頁面 { path: ‘/test’, component: test, meta: { requiresAuth: true } }, // loading頁面 { path: ‘/loading’, name: “loading”, component: loading, meta: { requiresAuth: true } },

  // 主頁
      {
        path: '/home',
        component: home,
        meta: {
          requiresAuth: true
        }
      },
      // 使用者管理
      {
        path: '/user',
        component: user,
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/user/add',
        name: 'addUser',
        component: addUser,
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/user/edit',
        name: 'editUser',
        component: editUser,
        meta: {
          requiresAuth: true
        }
      },
      // 選單管理
      {
        path: '/menu',
        name: 'menu',
        component: menu,
        meta: {
          requiresAuth: true
        }
      },
      // 雨傘管理
      {
        path: '/umbrella',
        name: 'umbrella',
        component: umbrella,
        meta: {
          requiresAuth: true
        }
      },
      // 租借點管理
      {
        path: '/location',
        name: 'location',
        component: location,
        meta: {
          requiresAuth: true
        }
      },
      // 訂單管理
      {
        path: '/order',
        name: 'order',
        component: order,
        meta: {
          requiresAuth: true
        }
      },
    ]
  }
];

// 頁面重新整理時,重新賦值有沒登入
if (window.localStorage.getItem('isLogin')) {
  store.commit('setIsLogin', window.localStorage.getItem('isLogin'));
}

const router = new Router({
  routes
});

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requiresAuth)) {  // 判斷該路由是否需要登入許可權
    console.log(store.getters.isLogin);
    if (store.getters.isLogin) {  // 通過vuex 如果當前有登入
      next();
    }
    else {
      console.log("沒有登入吖")
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    }
  }
  else {
    next();
  }
});

export default router;

這裡有四個需要重點關注的地方(引入和使用就不納入其中了): 1.單獨一個routes陣列用來存放路由變數,然後每一個路由物件都需要有個meta引數,裡面有個requiresAuth(也可以命其他名),這個就是用來判斷這個頁面需不需要判斷許可權,所以login頁面為false,其他頁面都為true。

在這裡插入圖片描述

2.new一個router物件,剛剛在注意點1的陣列作為引數,然後最後匯出這個router物件給其他頁面引用。 3.要有一個判斷頁面重新整理,重新賦值有沒登入。這個時候判斷localStorage中的isLogin,如果為true,所以重新整理前是有登入的,則提交觸發vuex更改狀態。 4.vue-router提供的鉤子函式,在路由更換的時候,都會觸發這個函式,這個時候就要用到注意點1的meta.requiresAuth,如果即將要進入的頁面需要判斷登入許可權,檢測vuex的isLogin,為true就可以進去,不然都跳轉到登入頁面。

二、Vuex

在這裡插入圖片描述

三 、modules/login.js

const login = {
  state: {
    // true為已經登入,false為沒登入
    isLogin: false
  },
  mutations: {
    setIsLogin(state, isLogin) {
      state.isLogin = isLogin;
    }
  },
  actions: {
    
  },
}

export default login;

getters.js

const getters = {
  isCollapse: state => state.nav.isCollapse,
  isLogin: state => state.login.isLogin
};
export default getters

index.js

import Vue from 'vue';
import Vuex from 'vuex';
import nav from './modules/nav'
import login from './modules/login'
// import app from './modules/app';
// import user from './modules/user';
// import menu from './modules/menu';
import getters from './getters';

Vue.use(Vuex);

const store = new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  modules: {
    nav,
    login
    // app,
    // user,
    // menu
  },
  getters
});

export default store

三、實際使用–>登入

handleSubmit() {
        this.$refs["loginForm"].validate((valid) => {
          if (valid) {
            if(this.loginForm.userName === "admin" && this.loginForm.password === "admin") {
              this.$notify({
                title: '恭喜你',
                message: '登入成功!',
                type: 'success'
              });
              // 觸發setIsLogin方法改變vuex中isLogin的值,
              this.$store.commit('setIsLogin', true);
             // 改變localStorage中isLogin的值,
              window.localStorage.setItem('isLogin', true);
              // Cookies.set('Token', response.data.token)
              this.$router.push({path: '/home'});

            }
            else {
              this.$message({
                message: '登入失敗:密碼錯誤!',
                type: 'warning'
              });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
},

四、實際使用–>退出登入

handleCommand(command) {
        if(command === "exit") {
          // 觸發setIsLogin方法改變vuex中isLogin的值,
          this.$store.commit('setIsLogin', false);
          // 改變localStorage中isLogin的值,
          window.localStorage.setItem('isLogin', false);
          this.$notify({
            title: '退出登入成功',
            message: '請重新登入',
            type: 'success'
          });
          this.$router.push({path: '/login'});
        }
}
<dropdown @command="handleCommand">
      <span class="el-dropdown-link">
        歡迎你,{{name}}<i class="el-icon-arrow-down el-icon--right"></i>
      </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="exit">退出登入</el-dropdown-item>
        </el-dropdown-menu>
</dropdown>