vuex存储后端返回的字典

47 阅读1分钟

在Vue.js中使用Vuex来管理应用程序状态非常有用。要将从后端获取到的字典数据存储在Vuex中,可以按照以下步骤进行操作:

  1. 首先,创建一个新的store模块(module)来处理与字典相关的状态。可以通过createStore()函数或者单文件组件的形式定义该模块。
// store/modules/dictionary.js
const dictionary = {
  state() {
    return {
      data: {} // 初始化为空对象
    }
  },
  mutations: {
    SET_DICTIONARY(state, payload) {
      state.data = payload;
    }
  },
  actions: {
    fetchDictionary({ commit }) {
      // 发起网络请求并获取字典数据
      axios.get('/api/dictionary')
        .then((response) => {
          const dictData = response.data;
          commit('SET_DICTIONARY', dictData);
        });
    }
  },
  getters: {
    getDictionaryItem: (state) => (key) => {
      if (!state.data[key]) {
        console.warn(`No item found for key ${key}`);
        return null;
      } else {
        return state.data[key];
      }
    }
  }
}
export default dictionary;
  1. 然后,在主store中注册这个模块。
import Vue from 'vue';
import Vuex from 'vuex';
import dictionaryModule from './modules/dictionary';
 
Vue.use(Vuex);
 
const store = new Vuex.Store({
  modules: {
    dictionary: dictionaryModule
  }
});
 
export default store;
  1. 最后,在需要访问字典数据的地方,可以通过
  created() {
    // 获取字典项数据
    this.$store.dispatch('fetchDictionary');
  },

来调度action来获取字典数据,并且可以通过

<template>
  <div>{{ getDictionaryItem('key') }}</div> <!-- 显示key对应的value -->
</template>
 
<script>
import { mapGetters } from 'vuex';
 
export default {
  computed: {
    ...mapGetters(['getDictionaryItem'])
  }
};
</script>

 return this.$store.getters['getDictionaryItem']('key');

来获取相应字典值。