【问题标题】:setting tha data array to a initial value after editing that array在编辑该数组后将数据数组设置为初始值
【发布时间】:2023-01-27 16:23:54
【问题描述】:

有没有一种方法可以让 Vue.js 在使用方法更改数据数组 arr 后将其设置为初始值?我已经更改了复选框及其值,现在想将数据数组重置为初始状态。


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

【问题讨论】:

    标签: javascript arrays vue.js methods reset


    【解决方案1】:

    我的建议是将默认值保存在其他地方,例如:

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

    请注意扩展语法 [...] 是必要的,因为您不想改变默认数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2011-12-24
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多