代码之家  ›  专栏  ›  技术社区  ›  Thuan Nguyen

使用vuex更新数据

  •  9
  • Thuan Nguyen  · 技术社区  · 6 年前

    作为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 对象在控制台中。它正好显示了我的预期。 但在点击更新按钮之后。它没有改变。

    任何人都可以告诉我原因并给我解决方案??谢谢

    4 回复  |  直到 6 年前
        1
  •  14
  •   ittus    6 年前

    可以将参数包装为1 payload 对象:

    在你的组件中

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

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

    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'});
      })
    }
    
        2
  •  3
  •   estani    5 年前

    更简单的是,只需使用方法来修改数组(不要直接修改它们)(请检查以下内容: 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
  •  1
  •   Khawer Zeshan    5 年前

    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
  •  0
  •   Serhan C.    4 年前

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

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