溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

VUEX狀態(tài)倉庫管理的方法

發(fā)布時間:2022-08-10 14:37:07 來源:億速云 閱讀:256 作者:iii 欄目:編程語言

這篇文章主要介紹“VUEX狀態(tài)倉庫管理的方法”,在日常操作中,相信很多人在VUEX狀態(tài)倉庫管理的方法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”VUEX狀態(tài)倉庫管理的方法”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。簡單來說就是:應(yīng)用遇到多個組件共享狀態(tài)時,使用vuex。

VueX 是一個專門為 Vue.js 應(yīng)用設(shè)計(jì)的狀態(tài)管理構(gòu)架,統(tǒng)一管理和維護(hù)各個vue組件的可變化狀態(tài)

場景:多個組件共享數(shù)據(jù)或者是跨組件傳遞數(shù)據(jù)時

vuex的五個核心概念:

  • State:共享狀態(tài),vuex的基本數(shù)據(jù),用來存儲變量,相當(dāng)于組件data里的數(shù)據(jù),只不過此時變成了全局變量。

  • Getter:基于state的派生狀態(tài),相當(dāng)于組件中的computed中的屬性。

  • Mutation:更改vuex中store共享狀態(tài)的方法,通過提交mutation來去修改狀態(tài),進(jìn)行同步操作數(shù)據(jù),通常用于action獲取異步數(shù)據(jù),獲取通過commit提交數(shù)據(jù)給mutation,在mutation同步操作state中的數(shù)據(jù)。

  • action:支持異步操作,可用于異步獲取請求中的數(shù)據(jù),并將獲取的數(shù)據(jù)同步commit提交給mutation,實(shí)現(xiàn)ajax異步請求數(shù)據(jù),mutation將其數(shù)據(jù)同步到state中。

  • modules:模塊化vuex,為了方便后期對于項(xiàng)目的管理,可以讓每一個模塊擁有自己的state、mutation、action、getters,使得結(jié)構(gòu)非常清晰,方便管理。

優(yōu)勢和劣勢有哪些?
優(yōu)勢主要就是可以全局共享數(shù)據(jù),方法。方便統(tǒng)一管理
劣勢的話,頁面刷新后state的變量都會還原清空,不會像cookies一樣持久性存儲

頁面刷新后vuex的state數(shù)據(jù)丟失怎么解決?
先說一下為什么會丟失呢?
因?yàn)閟tore里的數(shù)據(jù)是保存在運(yùn)行內(nèi)存中的,當(dāng)頁面刷新時頁面會重新加載vue實(shí)例,store里面的數(shù)據(jù)就會被重新賦值

如何避免?
其實(shí)主要還是看使用的場景是怎樣的,如果想某些數(shù)據(jù)持久性保留也可以搭配使用cookies或者localStorage。比如一些登錄的信息等。
比如請求拿到了登錄信息后可以先存在localStorage,將state里的變量值和sessionStorage里面的綁定,mutations中修改的時候同時修改state和localStorage。最后頁面直接使用vuex中的變量。


正式進(jìn)入使用

vuex的安裝
打開終端,輸入命令行npm install vuex --save進(jìn)行下載vuex

vuex應(yīng)用核心管理倉庫 構(gòu)建store

這里新建store文件夾,創(chuàng)建一個js取名為index.js,
在index里 ,通過將state,mutations,actions,getters引入到store中,并暴露出store對象。

下面為index.js的代碼

/*
  vuex最核心的管理對象 store
*/import Vue from 'vue';import Vuex from 'vuex';
 // 分別引入這四個文件  這四個文件的內(nèi)容和用法在下面分別講到import state from './state';import mutations from './mutations';import actions from './actions';import getters from './getters';
 //聲明使用插件Vue.use(Vuex)//new 一個Vuex的對象,將state,mutation,action,getters配置到vuex的store中,方便管理數(shù)據(jù)export default new Vuex.Store({  
  state,
  mutations,
  actions,
  getters,})

掛載store到vue實(shí)例上
main.js中

import store from './store'// ..........new Vue({
  el: '#app',
  router,
  store,   // ***
  render: h => h(App)})

state狀態(tài)管理數(shù)據(jù)

我們通常將需要進(jìn)行管理的共享數(shù)據(jù),放入state中,使其形似為全局變量,對于需要的組件進(jìn)行引入該state狀態(tài)數(shù)據(jù)。

const state = {
  userId: '',
  token: '',
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  tenantId: 1,
  userInfo: null};

mutations 同步提交數(shù)據(jù)

mutations用于更改state中的狀態(tài)邏輯的,且為同步更改state中的狀態(tài)數(shù)據(jù)。
需要知道的是在vuex中只能通過mutation來去修改state對象,
可以通過獲取actions獲取到的數(shù)據(jù)去修改state,也可以在mutations模塊中直接定義方法來去更改狀態(tài)數(shù)據(jù)。

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERID: (state, userId) => {
    state.userId = userId;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_TENANTID: (state, roles) => {
    state.tenantId = roles;
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
  }};

通過mutations和下面的actions模塊,大家也可以看出commit是用于調(diào)用mutation模塊中的。
在組件中調(diào)用其mutation模塊的代碼為:

this.$store.commit('SET_TOKEN', token_data)

actions 的異步操作

actions與其mutations類似,但其可以進(jìn)行異步操作,
且將異步操作獲取的數(shù)據(jù)提交給mutations,使得mutations更改state中的狀態(tài)數(shù)據(jù), 這里常常用于獲取ajax請求中的數(shù)據(jù)(因?yàn)槭钱惒?,并將其獲取的數(shù)據(jù)commit提交給mutations 使得 state數(shù)據(jù)狀態(tài)的更新。

和mutations 的不同之處在于:

  1. Action 提交的是 mutation,而不是直接變更狀態(tài)。

  2. Action 可以包含任意異步操作。

舉例

/* 下面就是通過actions執(zhí)行異步Ajax請求,
得到數(shù)據(jù)后,
通過commit的方法調(diào)用mutations 從而更新數(shù)據(jù)
例如:  commit('SET_TOKEN', data.uuid);
*/const actions = {
  login({ commit }, userInfo) {  // 用戶登錄
    const params = userInfo;
    params.userName = userInfo.userName.trim()
    return new Promise((resolve, reject) => {
      getLogin(params)
        .then((response) => {
          const { status, message, data } = response || {};
          if (status === 200) {
            // 存入 參數(shù): 1.調(diào)用的值 2.所要存入的數(shù)據(jù)
            commit('SET_USER_INFO', data);
            commit('SET_TOKEN', data.uuid);
            commit('SET_USERID', data.id);
            commit('SET_ROLES', data.roles);
            commit('SET_NAME', data.realName);
            commit('SET_TENANTID', data.tenantId || 1);
            setToken(data.uuid);
            db.save('userInfo', data);
            db.save('tenantId', data.tenantId || 1);
            localStorage.setItem('loginToken', data.uuid);
            resolve(data);
          } else {
            // ElementUI.Message.error(message);  // axios攔截統(tǒng)一提示了
          }
        })
        .catch((error) => {
          // ElementUI.Message.error(error.message); // axios攔截統(tǒng)一提示了
          reject(error);
        });
    });
  },}

這個actions在組件中的調(diào)用方法就是:

 this.$store.dispatch('user/login', postUser)
            .then(res => {
               // .............
              })// 我這里的login方法寫在了user.js這個module里 所以這里調(diào)用是 user/login// 下面會講到module

Getters 對state進(jìn)行加工

Getters相當(dāng)于computed計(jì)算屬性,用于加工處理state狀態(tài)數(shù)據(jù),有其兩個默認(rèn)參數(shù),第一個默認(rèn)參數(shù)為state,第二個默認(rèn)參數(shù)為getters。

const getters={
  plusCount(state){
    return state.count + 1
  },
 //獲取state中狀態(tài)數(shù)據(jù)對象,和獲取getters模塊中plusCount數(shù)據(jù)
  totalCount(state,getters){
    return getters.plusCount + state.count  }}

在組件中調(diào)用該方法的代碼片段為:

this.$store.getters.totalCount()

在Vue組件中獲得Vuex狀態(tài)

store實(shí)例中讀取狀態(tài)最簡單的方法就是在計(jì)算屬性中返回某個狀態(tài),由于Vuex的狀態(tài)存儲是響應(yīng)式的,所以在這里每當(dāng)store.state.count變化的時候,都會重新求取計(jì)算屬性,進(jìn)行響應(yīng)式更新。

 computed: {
        count: function(){
            return this.$store.state.count        }
    },

那么對于以上的store我們就簡單介紹完了,相信大家看完后對于vuex會有一定的理解。那么這個時候我們要想,是不是使用this.$store.statethis.$store.getters.xxx感到麻煩呢?下面我們介紹另一種引入state和getters的方式

輔助函數(shù) mapState 和 mapGetters

對于上述的在組件中引用state和getters的方法是不是感到麻煩呢?使用mapState你將會感受到便利。
組件中這樣使用

//首先我們需要先將輔助函數(shù)引入import { mapGetters,mapState } from 'vuex'
 export default {
 computed: {

  // 使用對象展開運(yùn)算符將 getter 混入 computed 對象中
  ...mapGetters( ['plusCount','totalCount'] )

 // 使用對象展開運(yùn)算符將 state 混入 computed 對象中
    ...mapState( ['userInfo','count'] )

 },methods:{
    getData(){
        // 這里就能直接使用了  直接使用state 和getters里的數(shù)據(jù)
        //  this.userInfo 
        // this.plusCount
        
    }}}

Module子模塊化管理

store文件夾下的index.js代碼如下

import Vue from 'vue'import Vuex from 'vuex'import getters from './getters'Vue.use(Vuex)const modulesFiles = require.context('./modules', true, /\.js$/)const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules}, {})const store = new Vuex.Store({
  modules,
  getters})export default store

文件目錄如圖

VUEX狀態(tài)倉庫管理的方法

舉例 api.js

import { getKey, getLogin, logout, getInfo } from '@/api/user';import { setToken, removeToken } from '@/utils/auth';import db from '@/utils/localstorage';import router, { resetRouter } from '@/router';import ElementUI from 'element-ui';const state = {
  userId: '',
  token: '',
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  tenantId: 1,
  userInfo: null
  // roles: ['9999']};const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERID: (state, userId) => {
    state.userId = userId;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_TENANTID: (state, roles) => {
    state.tenantId = roles;
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
  }};const actions = {
  // 獲取密鑰
  getKey({ commit }) {
    return new Promise((resolve, reject) => {
      getKey()
        .then((response) => {
          resolve(response);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 用戶登錄
  login({ commit }, userInfo) {
    // const { username, password } = userInfo;
    const params = userInfo;
    params.userName = userInfo.userName.trim()
    return new Promise((resolve, reject) => {
      // console.log(username, password);
      // setToken(state.token)
      // localStorage.setItem('loginToken', state.token)
      getLogin(params)
      // getLogin({ userName: username.trim(), password: password })
        .then((response) => {
          const { status, message, data } = response || {};
          if (status === 200) {
            // 存入 參數(shù): 1.調(diào)用的值 2.所要存入的數(shù)據(jù)
            commit('SET_USER_INFO', data);
            commit('SET_TOKEN', data.uuid);
            commit('SET_USERID', data.id);
            commit('SET_ROLES', data.roles);
            commit('SET_NAME', data.realName);
            commit('SET_TENANTID', data.tenantId || 1);
            setToken(data.uuid);
            db.save('userInfo', data);
            db.save('tenantId', data.tenantId || 1);
            localStorage.setItem('loginToken', data.uuid);
            resolve(data);
          } else {
            // ElementUI.Message.error(message);  // axios攔截統(tǒng)一提示了
          }
        })
        .catch((error) => {
          // ElementUI.Message.error(error.message); // axios攔截統(tǒng)一提示了
          reject(error);
        });
    });
  },

  // 獲取用戶信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response;
          data.roles = response.data.rights.map(String);
          if (!data) {
            reject('驗(yàn)證失敗,請重新登錄。');
          }
          const loginMessage = {
            memberId: data.id,
            userName: data.name,
            userTel: data.mobile,
            realName: data.realName,
            incorCom: data.incorCom,
            virtualCor: data.virtualCor,
            deptId: data.deptId,
            deptpath: data.deptpath,
            deptName: data.deptName          };
          localStorage.setItem('loginMessage', JSON.stringify(loginMessage));
          const { id, roles, realName } = data;
          // 角色必須是非空數(shù)組!
          if (!roles || roles.length <= 0) {
            reject('getInfo: 角色必須是非空數(shù)組!');
          }
          commit('SET_USERID', id);
          commit('SET_ROLES', roles);
          commit('SET_NAME', realName);
          localStorage.setItem('userRights', roles);
          // commit('SET_AVATAR', avatar)
          // commit('SET_INTRODUCTION', introduction)
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 用戶登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          db.remove('router');
          removeToken();
          resetRouter();
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 刪除token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      removeToken();
      resolve();
    });
  },

  // 動態(tài)修改權(quán)限
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async(resolve) => {
      const token = role + '-token';

      commit('SET_TOKEN', token);
      setToken(token);

      const { roles } = await dispatch('getInfo');
      console.log(roles, 'rolesrolesroles');
      resetRouter();

      // 根據(jù)角色生成可訪問路由映射
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      });

      // 動態(tài)添加可訪問路由
      router.addRoutes(accessRoutes);

      // 重置已訪問視圖和緩存視圖
      dispatch('tagsView/delAllViews', null, { root: true });

      resolve();
    });
  }};export default {
  namespaced: true,
  state,
  mutations,
  actions};

這樣后可以按功能分module使用

頁面中調(diào)用就是

// 使用mutationsthis.$store.commit('api/SET_T', keys);// 使用actionsthis.$store.dispatch('user/login', postUser).then(res => {})// 如果沒有分module // 那就是 this.$store.commit('SET_T', keys);// 直接調(diào)用方法

到此,關(guān)于“VUEX狀態(tài)倉庫管理的方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI