Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

setting tha data array to a initial value after editing that array

Is there a way Vue.js provides setting data array arr to the initial value, after it had being changed with methods ? I’ve changed the checkboxes and its values and now want to reset the data array to initial state.


<template>
  <div>
    <h1>Example 1</h1>
    <div
      v-for="(a, i) in arr"
      :key="i"
      :checked="a"
      @click="toggleItem(i)"
      class="checkbox"
    >
      <div class="out">{{ a }}</div>
    </div>
    <div class="out">{{ arr }}</div>
    <div class="out">{{ newArr }}</div>
    <!-- <div class="out">{{ newArr }}</div> -->
    <input @click="resetState" type="button" value="Reset" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [true, false, true, false, true, true, true]
    };
  },
  methods: {
    toggleItem(index) {
      this.arr.splice(index, 1, !this.arr[index]);
    },
    resetState() {
      // set the array arr to initial data after some toggleItem() changes
    },
  },
};
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My suggestion is to save the default value somewhere else, such as:

<script>
const defaultArr = [true, false, true, false, true, true, true];

export default {
  data() {
    return {
      arr: [...defaultArr]
    };
  },
  methods: {
    toggleItem(index) {
      this.arr.splice(index, 1, !this.arr[index]);
    },
    resetState() {
      // set the array arr to initial data after some toggleItem() changes
      this.arr = [...defaultArr];
    },
  },
};
</script>

Note the spreading syntax [...] is neccessary since you don’t want to mutate the default array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading