vuex module 中的状态改变

0 原因

任务是做一个后台管理系统,组长从某地刨了一个后台基础版本改了改。我负责其中一个状态管理部分,原后台版本用了自动模块引入,于是我也整了一个,然后发现在module和state里用action方法还是有点不同的。

1 不同

image

// boxId 是模块名(自动化生成的,我也是佛了。。。)

// dispatch还要标注是哪个模块的,因此用到了 boxId/setBoxId这种看起来有点别扭的写法。

2 代码

// /store/index.js

/**
 * @description 导入所有 vuex 模块,自动加入namespaced:true,用于解决vuex命名冲突,请勿修改。
 */

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
const files = require.context("./modules", false, /\.js$/);
const modules = {};

files.keys().forEach((key) => {
  modules[key.replace(/(\.\/|\.js)/g, "")] = files(key).default;
});
Object.keys(modules).forEach((key) => {
  modules[key]["namespaced"] = true;
});
const store = new Vuex.Store({
  modules
});
export default store;

// /store/module/boxId.js

import { setSessionStorage, removeSessionStorage } from "../../config/sessionStorage"
import { getSessionStorage } from "../../config/sessionStorage"

const state = () => ({
    boxId: 0
})
const getters = {
    boxId: (state) => state.boxId,
}
const mutations = {
    setBoxId(state, boxId) {
        state.boxId = boxId
    },
    removeBoxId(state){
        state.boxId = 0;
    },
}
const actions = {
    setBoxId({ commit }, boxId) {
        setSessionStorage('boxId', boxId)
        let b = getSessionStorage('boxId');
        console.log('Set b: ', b);
        commit('setBoxId', boxId)
    },
    removeBoxId({ commit }) {
        removeSessionStorage('boxId');
        let b = getSessionStorage('boxId');
        console.log('Remove b: ', b);
        commit('removeBoxId')
    },
}
export default { state, getters, mutations, actions }

// sessionStorage.js

// 短时存储写入
export function setSessionStorage(key,value){
    if(typeof value === 'string'){
        return window.sessionStorage.setItem(key,value);
    }
    else{
        return window.sessionStorage.setItem(key,JSON.stringify(value));
    }
}

// 短时存储读取
export function getSessionStorage(key){
    try{
        return JSON.parse(window.sessionStorage.getItem(key))
    }
    catch(e){
        return window.sessionStorage.getItem(key);
    }
}

// 清除短时存储数据
export function removeSessionStorage(key){
    return window.sessionStorage.removeItem(key);
}

[这里是之前写过的随笔](持久化存储 - 乐盘游 - 博客园 (cnblogs.com))

[参考文章](在vue组件中访问vuex模块中的getters/action/state - 情三 - 博客园 (cnblogs.com))

3 效果

image

原文地址:https://www.cnblogs.com/lepanyou/p/15592277.html