如何将Vuex类型常量与模块命名空间一起使用?

时间:2017-12-05 04:36:50

标签: javascript vue.js vuejs2 vuex

我有这个Vuex模块:

//modules/things.js
const state = {
  firstThing: 'abc',
  secondThing: 'def',
};

const getters = {
  getFirstThing: state => state.firstThing,
  getSecondThing: state => state.secondThing,
};

const mutations = {
  setFirstThing: (state, payload) => state.firstThing = payload,
  setSecondThing: (state, payload) => state.secondThing = payload
};

const actions = {};

export default {
  namespaced: true,   // <------
  state,
  mutations,
  actions,
  getters
};

我使用namespaced: true flag并可以使用此模块:

this.$store.state.things.firstThing             // <-- return abc here
this.$store.commit('things/setFirstThing', 10)
this.$store.getters['things/getFirstThing']     // <-- return abc here

如果我将使用Vuex official example中的常量,并重构我的modules/things.js文件:

export const Types = {
  getters: {
    GET_FIRST_THING: 'GET_FIRST_THING',
    GET_SECOND_THING: 'GET_SECOND_THING',
  },
  mutations: {
    SET_FIRST_THING: 'SET_FIRST_THING',
    SET_SECOND_THING: 'SET_SECOND_THING',
  }
};

const getters = {
  [Types.getters.GET_FIRST_THING]: state => state.firstThing,
  [Types.getters.GET_SECOND_THING]: state => state.secondThing,
};

const mutations = {
  [Types.mutations.SET_FIRST_THING]: (state, payload) => state.firstThing = payload,
  [Types.mutations.SET_SECOND_THING]: (state, payload) => state.secondThing = payload
};

我将不得不使用名称空间前缀:

this.$store.commit('things/' + Types.mutations.SET_FIRST_THING, 10);
this.$store.getters['things/' +  + Types.getters.GET_FIRST_THING]  

如果我将模块名称空间前缀包含在Types常量中,我将不得不使用字符串前缀things/进行突变/操作/获取声明:

const getters = {
  ['things/' + Types.getters.GET_FIRST_THING]: state => state.firstThing,
  ['things/' + Types.getters.GET_SECOND_THING]: state => state.secondThing,
};

如何避免?

2 个答案:

答案 0 :(得分:7)

您可以通过namepsaced: false禁用命名空间,只使用带前缀的常量:

export const Types = {
  getters: {
    GET_FIRST_THING: 'THINGS_GET_FIRST_THING',    // your namespace without '/' slash
    GET_SECOND_THING: 'THINGS_GET_SECOND_THING',
  },
  // ...
}

- 它会起作用。

但是如果你仍然希望在模块中保留namepsace: true并使用常量,你可以定义两种类型的常量:公共私有

export const Types = {                                               // <-- public
  getters: {
    GET_FIRST_THING: 'things/GET_FIRST_THING',
    GET_SECOND_THING: 'things/GET_SECOND_THING',
  },
  mutations: {
    SET_FIRST_THING: 'things/SET_FIRST_THING',
    SET_SECOND_THING: 'things/SET_SECOND_THING',
  }
};

const _types = removeNamespace('things/', Types);                    // <-- private

然后仅在Vuex模块中使用私有_types

const getters = {
  [_types.getters.GET_FIRST_THING]: state => state.firstThing,       
  [_types.getters.GET_SECOND_THING]: state => state.secondThing,
};

//...

和公共Types外部模块:

// some-component.vue
this.$store.commit(Types.mutations.SET_FIRST_THING, 10);
this.$store.getters[Types.getters.GET_FIRST_THING]
// ...

还在新的removeNamespace文件中实现简单的namespace-helper.js功能:

export default function removeNamespace(namespace, types){
  return _.reduce(types, (typeObj, typeValue, typeName) => {
    typeObj[typeName] = _.reduce(typeValue, (obj, v, k)=>{
      obj[k] = v.replace(namespace, '');
      return obj;
    }, {});
    return typeObj;
  }, {});
}

答案 1 :(得分:0)

@hedin的

The answer为我出色地工作,谢谢!

我唯一遇到的问题是:

  1. 我正在使用Typescript。

  2. 这可能有点过于冗长,从而损害了可读性。但是类型安全性对我来说更重要,我愿意容忍一些冗长的类型检查。

受他的设计启发,我打字并减少了冗长程度。

(我正在使用Vue 3(带有复合API)+ Vuex 4(带有命名空间的模块)。

首先,我创建了namespace-helper.ts,如下所示:

import _ from "lodash";

type NamespaceHelper = {
  [name: string]: string;
};

// Enhanced from @hedin, see https://stackoverflow.com/a/47646215/1360592
export default (
  namespace: string,
  types: any,
  section: "getters" | "actions" | "mutations",
): NamespaceHelper => {
  return _.reduce(
    types,
    (typeObj: NamespaceHelper, typeValue, typeName) => {
      if (typeName === section) {
        return _.reduce(
          typeValue,
          (obj: NamespaceHelper, v, k) => {
            obj[k] = v.replace(namespace, "");
            return obj;
          },
          {},
        );
      }
      return typeObj;
    },
    {},
  );
};

然后在我的商店模块中,我有:

const namespace = "things";

// For external use
export const Types = {
  getters: {
    GET_FIRST_THING: `${namespace}/GET_FIRST_THING`,
    GET_SECOND_THING: `${namespace}/GET_SECOND_THING`,
  },
  actions: {
    DO_FIRST_THING: `${namespace}/DO_FIRST_THING`,
    DO_SECOND_THING: `${namespace}/DO_SECOND_THING`,
  },
  mutations: {
    SET_FIRST_THING: `${namespace}/SET_FIRST_THING`,
    SET_SECOND_THING: `${namespace}/SET_SECOND_THING`,
  },
};

// For internal use in the same store
const _getters = removeNamespace(`${namespace}/`, Types, "getters");
const _actions = removeNamespace(`${namespace}/`, Types, "actions");
const _mutations = removeNamespace(`${namespace}/`, Types, "mutations");

// getters
const getters: GetterTree<MyStoreState, RootState> = {
  [_getters. GET_FIRST_THING]: (state) => {
    return state.blah;
  },
  ...
};

// actions
const actions: ActionTree<MyStoreState, RootState> = {
  [_actions.DO_FIRST_THING]: ({ commit }) => {
    // do stuff here
    ...
    commit(_mutations.SET_FIRST_THING);
  },
};

// mutations
const mutations = {
  [_mutations.SET_FIRST_THING]: (state: MyStoreState) => {
    state.blah = "foo";
  },
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
};

这是我从组件中使用它的方式:

<script lang="ts">
// imports go here, not shown for brevity

import { Types } from "@/store/modules/things";

export default defineComponent({
  name: "Thing",
  setup(props) {
    const store = useStore<RootState>();

    // I prefer singular for consuming getters and actions externally.
    const { getters: getter, actions: action } = Types;

    const firstThing = computed<ThingType>(() =>
      store.getters[getter.GET_FIRST_THING],
    );

    store.dispatch(action.DO_FIRST_THING);

    return {
      firstThing,
    };
  },
});
</script>