无法访问函数内的vuex状态

时间:2020-05-19 15:16:22

标签: javascript vue.js vuex

我正在开发Laravel + Vue应用程序。我正在使用Vuex进行状态管理。我正在尝试验证我的表格。一切进展顺利,但是我遇到了一个问题。问题是,当我第一次尝试提交表单时,validationError状态返回null(默认状态不是更新的状态)。当我再次提交表单(以检查验证)时,它将validationError对象记录在控制台中。谁知道为什么validationErrors状态在第一次提交时为空。

注意:当我尝试访问模板内的validateErrors状态时,它 效果很好

store.js

import Vue from "vue";
import Vuex from "vuex";
import categories from "./modules/categories";

Vue.use(Vuex);

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

categories.js

import axios from "axios";

const state = {
    categories: [],
    validation_errors: null
};

const getters = {
    allCategories: state => state.categories,
    validationErrors: state => state.validation_errors
};

const actions = {
    async fetchCategories({ commit }) {
        const response = await axios.get("/api/categories");
        commit("setCategories", response.data);
    },

    async addCategory({ commit }, { name, sku, unit, image, details }) {
        try {
            const formData = new FormData();
            formData.append("name", name);
            formData.append("sku", sku);
            formData.append("unit", unit);
            formData.append("image", image);
            formData.append("details", details);

            const res = await axios.post("/api/categories/add", formData);

            commit("newCategory", res.data);
        } catch (err) {
            const errors = err.response.data.errors;
            commit("formErrors", errors);
        }
    }
};

const mutations = {
    setCategories: (state, categories) => (state.categories = categories),
    newCategory: (state, category) => state.categories.unshift(category),
    formErrors: (state, errors) => (state.validation_errors = errors)
};

export default {
    state,
    getters,
    actions,
    mutations
};

AddCategoryForm.vue

<template>
  <form role="form" v-on:submit.prevent="handleSubmit">
        <label for="name">Category Name</label>
        <input
          type="text"
          class="form-control"
          name="name"
          id="name"
          placeholder="Category Name"
          v-model="category.name"
        />

       <button type="submit" class="btn btn-primary">Add Category</button>


    <!-- NOTE: I can access 'validationErrors' state here in the template -->


  </form>
</template>

<script>
import { mapActions, mapGetters } from "vuex";

export default {

  data() {
    return {

      category: {
        name: ""
      }
    };
  },
  computed: {
    ...mapGetters(["validationErrors"])
  },
  methods: {
    ...mapActions(["addCategory"]),

    handleSubmit() {
      this.addCategory(this.category);

      console.log(this.validationErrors); // returns `null` on first submit
    }
  }
};
</script>

1 个答案:

答案 0 :(得分:0)

操作 addCategory 是异步的,因此这就是为什么您应该在检查 this.validationErrors

之前等待它
 async handleSubmit() {
      await this.addCategory(this.category);

      console.log(this.validationErrors); // returns `null` on first submit
    }

OR

 handleSubmit() {
      this.addCategory(this.category),then(() => {
         console.log(this.validationErrors); // returns `null` on first submit
      });
    }