【问题标题】:Why isnt my Vuex modules working? [vuex] unknown mutation type: moduleName/mutation为什么我的 Vuex 模块不工作? [vuex] 未知突变类型:moduleName/mutation
【发布时间】:2021-03-26 14:25:39
【问题描述】:

我已经搜索了几个小时,但我不明白为什么会出现此错误: [vuex] 未知的突变类型:groceryStore/getStoreApple 在所有对杂货店模块中的突变的提交上。 据我所知,我是按书本做的。如果您对我在尝试使用杂货店模块中的功能时做错了什么有任何想法,请提供帮助。

这是我的 index.js: 位于 src/store/index.js

import Vue from "vue";
import Vuex from "vuex";
import * as groceryStore from "./modules/groceries";
Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
   groceryStore: groceries,
  }
});

这是我要访问的模块: src/store/modules/groceries.js

import { db } from "../../main";
const groceryStore = {
  namespace: true,
  state: {
    fruit: {},
    fish: {},
    meat: {},
    sauce: {},
    spices: {},
    vegetables: {},
    bakery: {},
    beverages: {},
  },
  mutations: {
    getStoreApple(state) {
      db.ref()
        .child("groceries")
        .child("Fruits")
        .child("Apple")
        .get()
        .then((usersObject) => {
          state.fruit = usersObject.val();
        });
    },
    getStoreFish(state) {
      db.ref()
        .child("groceries")
        .child("fish")
        .child("salmon")
        .get()
        .then((usersObject) => {
          state.fish = usersObject.val();
        });
    },
    getStoreMeat(state) {
      db.ref()
        .child("groceries")
        .child("meat")
        .child("chicken")
        .get()
        .then((usersObject) => {
          state.meat = usersObject.val();
        });
    },
    getStoreSauce(state) {
      db.ref()
        .child("groceries")
        .child("sauce")
        .child("mustard")
        .get()
        .then((usersObject) => {
          state.sauce = usersObject.val();
        });
    },
    getStoreSpices(state) {
      db.ref()
        .child("groceries")
        .child("spices")
        .child("chillipowder")
        .get()
        .then((usersObject) => {
          state.spices = usersObject.val();
        });
    },
    getStoreVegetables(state) {
      db.ref()
        .child("groceries")
        .child("vegtables")
        .child("carrot")
        .get()
        .then((usersObject) => {
          state.vegetables = usersObject.val();
        });
    },
    getStoreBakery(state) {
      db.ref()
        .child("groceries")
        .child("bakery")
        .child("bread")
        .get()
        .then((usersObject) => {
          state.bakery = usersObject.val();
        });
    },
    getStoreBeverages(state) {
      db.ref()
        .child("groceries")
        .child("beverages")
        .child("juices")
        .get()
        .then((usersObject) => {
          state.beverages = usersObject.val();
        });
    },
  },
  getters: {
    appleGetter(state) {
      return state.fruit;
    },
    fishGetter(state) {
      return state.fish;
    },
    meatGetter(state) {
      return state.meat;
    },
    sauceGetter(state) {
      return state.sauce;
    },
    spicesGetter(state) {
      return state.spices;
    },
    vegetablesGetter(state) {
      return state.vegetables;
    },
    bakeryGetter(state) {
      return state.bakery;
    },
    beveragesGetter(state) {
      return state.beverages;
    },
  },
};

export default groceryStore;

这是我尝试渲染代码的组件: src/views/Home.vue

<template>
  <div class="home">
    <h1 v-if="route">This is a {{ route }} page</h1>
    <div id="flexContainer">
      <div
        class="groceryNameContainer"
        v-for="grocery in groceries"
        :key="grocery.id"
      >
        <b-card
          title=""
          img-alt="Image"
          img-top
          tag="article"
          style="max-width: 20rem;"
          class="mb-2"
          ><b-card-img v-if="grocery.url" :src="grocery.url"></b-card-img>
          <b-card-text>
            {{ grocery.description }}
          </b-card-text>
          <b-card-text>
            {{ grocery.price }}
          </b-card-text>
          <b-card-text>
            {{ grocery.comparison }}
          </b-card-text>

          <b-button href="#" variant="primary">Add to Cart</b-button>
        </b-card>
      </div>
    </div>
    <router-view />
  </div>
</template>

<script>
// import { db } from "../main";
export default {
  data() {
    return {
      route: "",
    };
  },

  computed: {
    groceries: function() {
      var groceriesArray = [];
      groceriesArray.push(this.$store.getters["groceryStore/appleGetter"]);
      groceriesArray.push(this.$store.getters["groceryStore/fishGetter"]);
      groceriesArray.push(this.$store.getters["groceryStore/meatGetter"]);
      groceriesArray.push(this.$store.getters["groceryStore/sauceGetter"]);
      groceriesArray.push(this.$store.getters["groceryStore/spicesGetter"]);
      groceriesArray.push(this.$store.getters["groceryStore/vegetablesGetter"]);
      groceriesArray.push(this.$store.getters["groceryStore/bakeryGetter"]);
      groceriesArray.push(this.$store.getters["groceryStore/beveragesGetter"]);
      console.log(groceriesArray);
      return groceriesArray;
    },
  },

  created() {
    this.$store.commit("groceryStore/getStoreApple");
    this.$store.commit("groceryStore/getStoreFish");
    this.$store.commit("groceryStore/getStoreMeat");
    this.$store.commit("groceryStore/getStoreSauce");
    this.$store.commit("groceryStore/getStoreSpices");
    this.$store.commit("groceryStore/getStoreVegetables");
    this.$store.commit("groceryStore/getStoreBakery");
    this.$store.commit("groceryStore/getStoreBeverages");

    this.route = this.$route.name;
  },
};
</script>

<style>
.nestedGroceryInfoContainer {
  border: 1px solid black;
  margin: 10px;
  padding: 15px;
  border-radius: 5px;
}

.descriptionContainer {
  font-weight: 500;
  padding-top: 200;
  color: rgb(6, 6, 43);
}

.nav-text-collapse {
  background-color: rgb(0, 255, 13);
}
.nameContainer {
  font-weight: bold;
  text-decoration: underline;
}
.priceContainer {
  position: absolute;
  margin-top: 13%;
  border: none;
  font-weight: bold;
  font-size: 30px;
}

.groceryNameContainer > * {
  flex-basis: 45%;
}

#flexContainer {
  justify-content: center;
  display: flex;
  flex-wrap: wrap;
}
.innerProductContainer {
  margin-left: 28%;
  justify-content: center;
  display: flex;
  flex-wrap: wrap;
  margin-top: -65%;
  width: 30%;
  height: 46%;
}
.productImage {
  margin-left: 55px;
  height: 150px;
  width: 160px;
}
.detailsContainer {
  justify-content: center;
  display: flex;
  flex-wrap: wrap;
}
.comparisonContainer {
  color: #2f2626;
}
</style>

这里也是 main.js 文件:

import App from "./App.vue";
import router from "./router";
import store from "./store";
import Vue from "vue";



Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

【问题讨论】:

  • 我对 Vuex 有经验,但还没有使用过模块。但是,在快速查看文档后,您似乎缺少 Vuex 'modules' 属性:new Vuex.Store({ modules: { a: moduleA } })
  • 这是一个好点,但它并没有解决任何问题,我担心。仍然得到同样的错误:(
  • 我看到你已经添加了 Vue.use(Vuex) ,但我不知道你是否真的在 Vue 实例上添加了 store 。 (例如:在您的 main.js 文件中,您将拥有 new Vue({ el:"#app", store: store})
  • 如果您仍有问题,我建议您暂时将模块排除在外。只需在一个没有命名空间的文件中构建您的 Vuex 存储。一旦工作正常,您可以重新添加模块/命名空间,看看它是否再次中断。
  • 呵呵@Tim,这几乎就是我所做的,我很害怕。当它全部在路由器文件夹内的 Index.js 中时,它就像一个魅力。

标签: javascript vue.js vuex vuex-modules


【解决方案1】:

我们交换了几个 cmets 之后,我做了一些挖掘,发现了一个我最近构建的相当简单的 Vuex Module 示例。我在这里发布商店、模块和组件。

您的应用程序显然要复杂得多,但我注意到的一件事是,在您的 Vuex 商店中,您将模块导入编码为

import * as groceryStore from "./modules/groceries";

而在我的商店中,我将模块导入编码为

import userModule from './modules/user-store-module.js'

我不是 JavaScript 模块专家,但我想我会指出这一点。这是我的源文件:

编辑:我添加了命名空间、getter、突变和其他组件功能来使用它们。

/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

import userModule from './modules/user-store-module.js'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    userModule: userModule
  }
})

/store/modules/user-store-module.js

const userModule = {
  namespaced: true,
  state: () => ({
    users: [
      {
        id: 1,
        name: 'User1',
        gender: 'male'
      },
      {
        id: 2,
        name: 'User2',
        gender: 'female'
      },
      {
        id: 3,
        name: 'User3',
        gender: 'male'
      },
      {
        id: 4,
        name: 'User4',
        gender: 'female'
      },
    ]
  }),
  getters: {
    getMaleUsers: state => {
      return state.users.filter( user => user.gender === 'male')
    },
    getFemaleUsers: state => {
      return state.users.filter( user => user.gender === 'female')
    },
  },
  mutations: {
    addUser(state, newGender) {
      let nextId = state.users.length + 1;
      state.users.push({
        id: nextId,
        name: 'User' + nextId,
        gender: newGender
      })
    }
  }
}

export default userModule;

VuexModule.vue

<template>
  <div class="vuex-module">
    <div class="row">
      <div class="col-md-6">
        <h4>Users</h4>
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>ID</th>
              <th>NAME</th>
              <th>GENDER</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id">
              <td>{{ user.id }}</td>
              <td>{{ user.name }}</td>
              <td>{{ user.gender }}</td>
            </tr>
          </tbody>
        </table>
        <button type="button" class="btn btn-secondary" @click="addUser">Add Random User</button>
      </div>

      <div class="col-md-6">
        <div class="row">
          <div class="col-md-12">
            <h4>Male Users</h4>
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>NAME</th>
                  <th>GENDER</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in maleUsers" :key="user.id">
                  <td>{{ user.id }}</td>
                  <td>{{ user.name }}</td>
                  <td>{{ user.gender }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="row">
          <div class="col-md-12">
            <h4>Female Users</h4>
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>NAME</th>
                  <th>GENDER</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in femaleUsers" :key="user.id">
                  <td>{{ user.id }}</td>
                  <td>{{ user.name }}</td>
                  <td>{{ user.gender }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        gender: 'male'
      }
    },
    computed: {
      users() {
        return this.$store.state.userModule.users;
      },
      maleUsers() {
        return this.$store.getters['userModule/getMaleUsers'];
      },
      femaleUsers() {
        return this.$store.getters['userModule/getFemaleUsers'];
      }
    },
    methods: {
      addUser() {
        let nextGender = this.gender === 'male' ? 'female' : 'male';
        this.gender = nextGender;
        this.$store.commit('userModule/addUser', this.gender);
      }
    }
  }
</script>

【讨论】:

  • 一切看起来都很棒,只是我似乎无法找到我在做什么不同...我想知道它是否与我使用 Vue 2x 有关系?
  • 我想我可能已经找到了问题所在。查看问题中的“src/store/index.js”文件,您的导入是import * as groceryStore from "./modules/groceries";,但在new Vuex.Store() 中,您写了modules: { groceryStore: groceries, }。我认为应该是modules: { groceryStore: groceryStore, }(不是杂货),或者甚至缩短为modules: { groceryStore }。让我知道是否可以解决。
【解决方案2】:
import * as groceryStore from "./modules/groceries";

会给你一个从文件中导出的所有对象。(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#import_an_entire_modules_contents)

在你的情况下,它可能会给你一个对象

 {
     default: {}// your groceries object
    }

所以请尝试

 import groceryStore from "./modules/groceries";

【讨论】:

    猜你喜欢
    • 2018-02-06
    • 2019-10-07
    • 1970-01-01
    • 2021-11-13
    • 2021-04-04
    • 2018-08-17
    • 2019-07-02
    • 2017-10-13
    • 2021-11-28
    相关资源
    最近更新 更多