在登陸退出時候使用Vuex


1.登陸的時候,在登陸模塊請求接口,然后獲取一個access_token,獲取用戶權限.保存到緩存里面。

2.退出的時候,請求退出接口,把緩存里面的access_token清除。

 

一旦要在登陸里面做一些行為,比如,在后面新加一些數據傳遞給登陸接口,做數據收集。就要在登陸的Login.vue模塊

里面直接修改。模塊里面的代碼很多。所有的邏輯都混在一起。

 

所以可以把登陸和退出的變量和行為抽離出來,在狀態管理里統一管理。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

  

把退出,登陸的模塊都封裝在一個狀態模塊上面

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的狀態
store.state.b // -> moduleB 的狀態

  

對用戶權限判斷是否可以進入某個頁面的時候,統一在路由鈎子里進行執行。

比如 登陸進首頁,需要判斷用戶權限,從別的頁面進首頁,仍然要判斷用戶權限。

如果頁面進入分別寫在登陸頁面,和別的頁面,代碼就不好維護,都在vue路由的導航守衛里面進行處理

 

登陸異步代碼 ,和login模塊里面的回調。

state狀態管理里面, mutations是立即執行的,actions 可以是異步的,所以用actions。

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

const loginSet = {
    state: {
        access_token: null
    },
    mutations: {
         setAccessToken(state, param){
             state.access_token = param.value;
         }
    },
    actions: {
        loginAsync({ commit }){
            return new Promise((resolve, reject)=>{
                setTimeout(()=> {
                    commit({
                        type: 'setAccessToken',
                        value: 'ajshdksjjsd' //我隨便寫了幾個值
                    });
                    resolve();
                }, 1000)
            });
        }
    },
    getters: {

    }
};


const store = new Vuex.Store({
    modules: {
        login: loginSet
    }
})

export {store};  

登陸模塊的調用,異步回調

this.$store.dispatch('loginAsync').then(()=>{
           //如果登陸成功了以后,回調
           console.log(this.$store.state.login.access_token);
           this.$router.push('首頁');
 });

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM