1. 程式人生 > >Vue學習筆記三:使用vuex與localstorage管理登入許可權

Vue學習筆記三:使用vuex與localstorage管理登入許可權

使用vuex與localstorage管理登入許可權

此次採用vuex + localstorage 配合使用來管理使用者的登入狀態,只使用vuex的話在使用者進行重新整理時將會自動刪除,所以配合localstorage,這樣可以讓SPA應用中既可以同步用到資料,又不受重新整理影響,實現步驟如下:

下載並安裝vuex(具體可參見筆記一)
npm install vuex -S
在公用base.js中,設定localstorage方法,之後可以通過this.方法呼叫
Vue.prototype.setToken = function (tokenName, tokenValue)
{
if (window.localStorage) { localStorage.setItem(tokenName, tokenValue); } else { alert('This browser does NOT support localStorage'); } }; Vue.prototype.getToken = function (name) { var token = localStorage.getItem(name); if (token) { return token; } else
{ return ''; } };
在store.js中定義登入狀態
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  // 定義狀態
  state: {
    //登入狀態,預設為'',當登入成功後自動再更新狀態
    isLogin :'' 
  },
  mutations:{
    isLogin(state,msg){
      state.isLogin = msg;
      this.setToken('isLogin'
,msg) } } }) export default store

在登入或者註冊的登入成功時,改變isLogin狀態

 codeLogin() {
      if (this.codePhone == '') {
        this.pupUp('手機號不能為空')
      } else if (!this.phoneReg.test(this.codePhone)) {
        this.pupUp('手機號碼格式錯誤')
      } else if (this.code == '') {
        this.pupUp('請輸入驗證碼')
      } else if (!this.codeReg.test(this.code)) {
        this.pupUp('驗證碼格式不正確')
      } else {
        this.axios
          .post('/api/v1/nopass_login', {
            mobile: this.codePhone,
            verfiycode: this.code,
            openid: this.openid,
            client: 'wechat'
          })
          .then(res => {
            console.log(res)
            if (res.data.code == 0) {
              this.setToken('bulaapi_token', res.data.data.token)
              this.setToken('userInfo', JSON.stringify(res.data.data.user))
              let userInfo = this.getToken('userInfo')
              userInfo = JSON.parse(userInfo)
              this.setToken('user_phone', userInfo.mobile)
              this.pupUp('登入成功')

              //設定本地儲存及vuex倉庫中islogin的狀態值
              this.setToken('isLogin',100)
              this.$store.commit('isLogin',100)

              this.$router.push(this.$route.query.redirect)
            }
          }).catch(err=>{
            console.log(err)
          })
      }

在main.js中vue例項上進行判斷

new Vue({
  el: '#app',
  router,
  store,
  components: {
    App
  },
  template: '<App/>',
  created(){
    //判斷是否有本地儲存中是否有isLogin,並更新vuex倉庫
    if(this.getToken('isLogin') == null){
      this.setToken('isLogin','')
    }
    this.$store.state.isLogin = this.getToken('isLogin')
    console.log(this.$store.state.isLogin)
  }
})

在main.js中設定路由鉤子函式,在跳轉前進行判斷

import router from './router';
Vue.use(router);

router.beforeEach((to, from, next) => {
//設定延時器讓created先執行在進行路由跳轉
  setTimeout((res) => {
  // 判斷該路由是否需要登入許可權
    if (to.meta.requireAuth) { 
    // 通過vuex state獲取當前的狀態是否存在
      if (store.state.isLogin) { 
        next();
      } else {
        next({
          path: '/login',
          query: {
            redirect: to.fullPath
          } // 將跳轉的路由path作為引數,登入成功後跳轉到該路由
        })
      }
    } else {
      next();
    }
  }, 100);

在路由的index.js中對需要驗證的頁面進行設定

routes: [{
      path: '/',
      name: 'My',
      component: My,
      meta: {
        requireAuth: true, // 新增該欄位,表示進入這個路由是需要登入的
      },
    },
    ...
]