使用vue.set()更改属性无效

问题描述 投票:0回答:1

带有递增,递减,复位按钮的简单计数器,以及计数器的历史值列表:https://codepen.io/Olivier_Tvx/pen/JjdyBMO

我希望resetCounter()清除所有以前的历史记录。我不确定什么是正确的方法。我尝试将'visible'属性更改为'false'并在视图中对其进行过滤,但没有成功。

我收到错误:“ [Vue警告]:无法对未定义,空值或原始值设置未设置反应性:]

我做错了什么?我需要这里的vue.set吗?

JS

new Vue({
  el: '#app',
  data () {
                return {
                  historics: [{
                      value: '',
            visible: true,
                }],
        timer: 1000,
                counter: 0,
            }
        },
  methods: {
    increaseCounter() { // Increase
      clearTimeout(this.timer);
      this.counter++;
      this.timer = setTimeout(() => { this.pushToHistorics() }, 1000)
    },
    decreaseCounter() { // Decrease
      clearTimeout(this.timer);
      this.counter--;
      this.timer = setTimeout(() => { this.pushToHistorics() }, 1000),
        console.log(this.historics)
    }, 
    resetCounter() { // Reset
      this.counter = 0;
      for (historic in this.historics) {
         Vue.set(this.historic, 'visible', false);
       };
      // for (historic in this.historics) {
      // this.historic.push({visible: false});  
      // };
    },
    pushToHistorics() {
    this.historics.push({
      value: this.counter,
      visible: true,
    })
    }
  },
  computed: {
  }
});

HTML

<div class="flex-container align-center">
  <div id="app">
    <button @click="increaseCounter()" class="button rounded shadow success">
      Increase
    </button>
    <button @click="decreaseCounter()" class="button rounded shadow warning">
      Decrease
    </button>
    <button @click="resetCounter" class="button rounded shadow alert">
      Reset
    </button>
    <p class="text-center">
      Counter: {{ counter }} <br>
    </p>
    <ul>
    <li v-for="historic in historics.slice(0, 10)" v-if="historic.visible == true"> {{ historic.value }} - {{ historic.visible }}</li>
    </ul>
  </div>
</div>
vue.js set
1个回答
0
投票

例如:

resetCounter() {
    this.counter = 0;
    this.historics.forEach((historic, idx) => {
        historic.visible = false;
        Vue.set(this.historics, idx, historic);
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.