1

I'm trying to extract array from Vuex, edit it locally, then:

  1. Discard changes without changing the Vuex array, or
  2. Submit local changes (to backend).

At this point, editing the local array is also updating the array in Vuex -- which I don't want to.

When I edit the data on the form and return (without submit), the changes are also carried over the the array in Vuex instead of only modifying the local array.

Quick recap of my code:

Store:

 var app = new Vue({
        el: "#app",
        store: new Vuex.Store({
          state: {
            details: [ /* data */ ]
          }
        })
      });

HTML:

Note: Here I can see in what the default values are before edit.

    <b-form>
     // I'm using the item and index later on
     <div v-for="(item, index) in data">
       // Just want to see what the default values are before editing
       <b-form-input v-model="form.title"></b-form-input>
     </div>
    </b-form>

Script:

  data() {
    return {
      data: null,
      form: null
    }
  },
  beforeMount() {
    this.data = [...this.$store.state.details]
    this.form = this.data[0];
  }

How can I improve my code, so that I can make changes locally?

2 Answers 2

1

Use JSON Parse and Stringify to make a local copy of the Vuex State with no reactivity.

  beforeMount() {
    this.data = [...this.$store.state.details]
    this.form = JSON.parse(JSON.stringify(this.data[0]));
  }
Sign up to request clarification or add additional context in comments.

Comments

1

That's because it's only clone the array reference and not the objects inside and thats called 'shallow copy', the easiest way to solve this would be to map details array and clone the objects inside.

this.data = this.$store.state.details.map(i => Object.assign({}, i));

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.