【问题标题】:Update data using vuex使用 vuex 更新数据
【发布时间】:2018-10-29 04:12:09
【问题描述】:

作为 Vuex,我正在尝试使用表单更新对象。 我的代码是这样的。

店内:

const state = {
   categories: []
};

//mutations:
[mutationType.UPDATE_CATEGORY] (state, id, category) {
    const record = state.categories.find(element => element.id === id);
    state.categories[record] = category;
}

//actions:
updateCategory({commit}, id, category) {
  categoriesApi.updateCategory(id, category).then((response) => {
    commit(mutationType.UPDATE_CATEGORY, id, response);
    router.push({name: 'categories'});
  })
}

.Vue 文件中的模板:

    <form>
      <div class="form-group">
        <label for="Name">Name</label>
        <input
          type="text"
          class="form-control form-control-sm"
          name="name"
          v-model.lazy="category.name" required>
      </div>

      <div class="form-group">
        <label for="Slug">Slug</label>
        <input
          type="text"
          class="form-control form-control-sm"
          name="slug"
          v-model.lazy="category.slug" required>
      </div>

      <div class="form-group">
        <label for="Avatar">Avatar</label>
        <input
          type="text"
          class="form-control form-control-sm"
          name="avatar"
          v-model.lazy="category.avatar" required>
      </div>

      <div class="form-group">
        <label for="Description">Description</label>
        <textarea
          type="text"
          class="form-control form-control-sm"
          rows="5"
          name="description"
          v-model.lazy="category.description"></textarea>
      </div>

      <div class="form-group">
        <button type="submit" @click.prevent="updateCategory" class="btn btn-outline btn-sm">Update</button>
      </div>

    </form>

在脚本中:

export default {
    data() {
      return {
        category: {}
      }
    },

    methods: {
      getCategoryById(id) {
        axios.get(`categories/${id}`)
          .then(response => {
            this.category = response.data;
          })
          .catch(error => {
            console.log(error);
          })
      },

      // Using mutation.
      updateCategory() {
        this.$store.dispatch('updateCategory', this.$route.params.id, this.category);
        console.log(this.category); //Display exactly data changed.
      }
    },

    created() {
      this.getCategoryById(this.$route.params.id);
    }
}

我的问题是当我单击更新时。它没有任何改变。 我确实在控制台中打印了category Object。它完全符合我的预期。 但点击更新按钮后。它没有改变。

谁能告诉我为什么并给我解决方案?谢谢。

【问题讨论】:

  • 首先,动作和突变只接受两个参数。其次,你不能在 Vue 中更新这样的数组:state.categories[record] = category。见vuejs.org/v2/guide/list.html#Caveats
  • 感谢@Bert 的回复。那么如何用突变更新数组呢?

标签: javascript vue.js vuejs2 vuex


【解决方案1】:

您可以将参数包装在 1 个payload 对象中:

在你的组件中

this.$store.dispatch('updateCategory', {
  id: this.$route.params.id,
  data: this.category
});

在您的商店中,您需要在编辑 categories 数组时创建新对象(您可以阅读有关不可变的更多信息)

const state = {
   categories: []
};

//mutations:
[mutationType.UPDATE_CATEGORY] (state, payload) {
    state.categories = state.categories.map(category => {
      if (category.id === payload.id) {
        return Object.assign({}, category, payload.data)
      }
      return category
    })
}

//actions:
updateCategory({commit}, payload) {
  categoriesApi.updateCategory(payload.id, payload.data).then((response) => {
    commit(mutationType.UPDATE_CATEGORY, payload);
    router.push({name: 'categories'});
  })
}

【讨论】:

  • 为什么要创建一个新数组而不是调用splice
  • splice 不会更改对象引用,因此不会触发 Vue 反应性
【解决方案2】:

而且更简单,只需使用方法来修改数组(切勿直接修改它们)(检查此:https://vuejs.org/2016/02/06/common-gotchas/#Why-isn%E2%80%99t-the-DOM-updating 即使旧的和 DOM 相关,仍然有效)

所以只要找到你的对象并用你的突变中的拼接替换:

const index = state.objectsArray.map(o => o.id).indexOf(newObject.id);
state.objectsArray.splice(index, 1, newObject);

【讨论】:

    【解决方案3】:

    ES6更新方式

    //mutations UPDATE:
    [mutationType.UPDATE_CATEGORY] (state, payload) {
        state.categories = [
            ...state.categories.map(item => 
                item.id !== updatedItem.id ? item : {...item, ...updatedItem}
            )
        ]
    }
    
    //mutations CREATE:
    [mutationType.CREATE_CATEGORY] (state, category) {
        state.categories = [category, ...state.categories] //Append to start of array
    }
    
    //mutations DELETE:
    [mutationType.DELETE_CATEGORY] (state, id) {
        state.categories = [
           ...state.categories.filter((item) => item.id !== id)
        ];
    }
    

    【讨论】:

      【解决方案4】:

      你只需要一行代码,因为 javascript 对象有reference capabilities

      //mutations:
      [mutationType.UPDATE_CATEGORY] (state, id, category) {
          Object.assign(state.categories.find(element => element.id === id), category);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-24
        • 2020-05-18
        • 2021-11-13
        • 1970-01-01
        • 2019-10-05
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        • 2021-01-22
        相关资源
        最近更新 更多