Search code examples
javascriptarraysvue.jsmethodsreset

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

  • 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.