0

I am trying to update a single property of an object from an array using vuex.

here is my code in store file.

export default{
  namespaced: true,
  state: {
    customers: null,
  },
  mutations: {
    UPDATE_MODIFIED_STATE(state, value) {
      state.customers = [
        ...state.customers.filter(item => item.Id !== value.Id),
        value,
      ];
    },
  },

And below code is from my .vue file.

export default {
  computed: {
    customerArray() {
      return this.$store.state.CustomerStore.customers;
    },
  },
  methods: {
    ...mapMutations('CustomerStore', ['UPDATE_MODIFIED_STATE']),
    updateCustomers() {
      if(someCondition) {
        this.customerArray.forEach((element) => {
            element.IsModified = true;
            this.UPDATE_MODIFIED_STATE(element);
        });
      }
      /// Some other code here
    },
  },
};

As you can see I want to update IsModified property of object. It is working perfectly fine. it is updating the each customer object.

Just want to make sure, is it correct way to update array object or I should use Vue.set.

If yes, I should use Vue.set, then How can I use it here.

1 Answer 1

1

You are actually not mutating your array, what you do is replacing the original array with a new array generated by the filter function and the passed value. So in your example there is no need to use Vue.set.

You can find more information about replacing an array in the vue documentation.

The caveats begin however when you directly set an item with the index or when you modify the length of the array. When doing this the data will no longer be reactive, you can read more about this here.

For example, consider the following inside a mutation:

// If you update an array item like this it will no longer be reactive.
state.customers[0] = { Id: 0, IsModified: true }

// If you update an array item like this it will remain reactive.
Vue.set(state.customers, 0, { Id: 0, IsModified: true })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.