Update data using vuex

前端 未结 4 2039
Happy的楠姐
Happy的楠姐 2021-01-02 14:39

As Vuex, I\'m trying to update an object using form. My code like this.

In store:

const state = {
   categories: []
};

//mutations:
[mutationType.UP         


        
相关标签:
4条回答
  • 2021-01-02 15:11

    You just need one line code because the javascript object has reference capabilities

    //mutations:
    [mutationType.UPDATE_CATEGORY] (state, id, category) {
        Object.assign(state.categories.find(element => element.id === id), category);
    }
    
    0 讨论(0)
  • 2021-01-02 15:17

    ES6 way of updating

    //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)
        ];
    }
    
    0 讨论(0)
  • 2021-01-02 15:19

    You can wrap your parameters in 1 payload object:

    In your component

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

    in your store, you need to made new object when edit categories array (you can read more about 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'});
      })
    }
    
    0 讨论(0)
  • 2021-01-02 15:29

    and much more simple, just use methods to modify arrays (never modify them directly) (check this: https://vuejs.org/2016/02/06/common-gotchas/#Why-isn%E2%80%99t-the-DOM-updating even old and DOM related, is still valid)

    So just find your object and replace with splice in your mutation:

    const index = state.objectsArray.map(o => o.id).indexOf(newObject.id);
    state.objectsArray.splice(index, 1, newObject);
    
    0 讨论(0)
提交回复
热议问题