无法从单独的模块调度命名空间操作:[vuex]未知操作类型

时间:2018-04-23 00:40:53

标签: javascript vue.js vuex

我有两个模块activitiesalerts。添加activity后,我想使用命名空间操作alerts/SHOW调度警报。

当我直接从组件调用操作时(使用Vuex中的createNamespacedHelpers,命名空间为alerts),这是有效的。

但是当我从另一个命名空间模块调度操作时,我收到以下错误消息:

[vuex] unknown action type: SHOW

我不确定我做错了什么。

我正在使用另一个ADDcreateNamespacedHelpers命名空间调用activities操作。我还使用了Vuex module documentation中指出的{ root: true }选项。

AddActivityButton.vue

<template>
  <button @click="addActivity(activity)"
          type="button"
          :disabled="activityCount >= maxActivities"
          class="btn btn-secondary">{{ activity.name }}
  </button>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
import { ADD } from "@/store/modules/activities";

const { mapActions, mapGetters, mapState } = createNamespacedHelpers(
  "activities"
);

export default {
  methods: {
    ...mapActions({
      addActivity: ADD
    })
  },
  computed: {
    ...mapState(["maxActivities"]),
    ...mapGetters(["activityCount"])
  },
  props: {
    activity: {
      type: Object,
      required: true
    }
  }
};
</script>

activities.js

import uuid from "uuid/v4";
import { SHOW as SHOW_ALERT } from "@/store/modules/alerts";

export const ADD = "ADD";
export const RESET = "RESET";
export const MAX_ACTIVITIES = 15;

const state = {
  items: [
    { id: 1, name: "A" },
    { id: 2, name: "B" },
    { id: 3, name: "C" },
    { id: 4, name: "D" },
    { id: 5, name: "E" },
    { id: 6, name: "F" }
  ],
  activities: [],
  maxActivities: MAX_ACTIVITIES
};

const getters = {
  activityCount(state) {
    return state.activities.length;
  }
};

const mutations = {
  [ADD](state, activity) {
    state.activities = [...state.activities, { ...activity, id: uuid() }];
  },
  [RESET](state) {
    state.activities = [];
  }
};

const actions = {
  [ADD]({ dispatch, commit, getters }, activity) {
    if (getters.activityCount >= MAX_ACTIVITIES) {
      return null;
    }
    if (getters.activityCount > 1) {
      dispatch(SHOW_ALERT, null, { root: true }); // This is the problematic line.
    }
    commit(ADD, activity);
  }
};

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

alerts.js

export const SHOW = "SHOW";

const state = {
  show: false
};

const mutations = {
  [SHOW](state) {
    state.show = true;
  }
};

const actions = {
  [SHOW]({ commit }) {
    commit(SHOW);
  }
};

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

store.js

import Vue from "vue";
import Vuex from "vuex";
import activities from "./modules/activities";
import alerts from "./modules/alerts";

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    activities,
    alerts
  }
});

2 个答案:

答案 0 :(得分:8)

您必须在调度时将操作命名为:

dispatch('alerts/' + SHOW_ALERT, null, { root: true });

使用模板文字应为:

dispatch(`alerts/${SHOW_ALERT}`, null, { root: true });

答案 1 :(得分:0)

这是为了防止您从组件

派发一个模块存储的操作
this.$store.dispatch("alerts/SHOW", data);