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)"
>
<div >{{ a }}</div>
</div>
<div >{{ arr }}</div>
<div >{{ newArr }}</div>
<!-- <div >{{ 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>
CodePudding user response:
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.