【问题标题】:How to fix setInterval bugg?如何修复 setInterval 错误?
【发布时间】:2020-08-05 11:28:53
【问题描述】:

我有一个带 v-for 的 h1,我正在从我的数组中写出东西,它看起来像这样:

 <h1
        v-for="(record, index) of filteredRecords"
        :key="index"
        :record="record"
        :class="getActiveClass(record, index)"
      >
        <div :class="getClass(record)">
         
          <strong v-show="record.path === 'leftoFront'"
            >{{ record.description }}
          </strong>
          
        </div>
      </h1>

如您所见,我正在绑定一个类(getActiveClass(record,index) --> 将我的记录和索引传递给它)

这是我的 getActiveClass 方法:

getActiveClass(record, index) {
      this.showMe(record);

      return {
        "is-active": index == this.activeSpan
      };
    }

我正在调用一个名为 showMe 的函数,将我的记录传递给它,这就是问题开始的地方 showMe 方法适用于我的 setInterval,所以基本上它的作用是我的数组中有多个对象,并且它正在设置间隔,因此当该记录的 record.time 结束时,它会切换到下一个。看起来像这样:

 showMe(record) {
     console.log(record.time)
      setInterval(record => {

        if (this.activeSpan === this.filteredRecords.length - 1) {
          this.activeSpan = 0;
        } else {
          this.activeSpan++;
        }
      }, record.time );
    },

此 activeSpan 确保 'is-active' 类(见上文)正确更改。

现在我的问题是,当我打印出来时,record.time 无法正常工作,例如,如果我的数组中有两个对象,它控制台会记录我两次。 所以它没有正确地改变它的记录。时间它只是改变得非常快,随着时间的流逝,它显示出我的记录的循环非常快。

这是为什么呢?我怎样才能正确设置它,以便当我得到一个记录时,它的间隔将是 record.time(属于它),并且当记录更改时它再次执行相同的操作(听它的 record.time)

例如:

filteredRecords:[
{
description:"hey you",
time:12,
id:4,
},
{
description:"hola babe",
time:43,
id:1
},


]

它应该首先显示“hey you”文本,它应该显示 12 秒,然后它应该显示“hola babe” 43 秒。

谢谢

【问题讨论】:

  • 使用setTimeout() 而不是setInterval()
  • 这对先生没有帮助,它甚至在快速变化,不听它的记录。时间,我控制台。注销它,它给了我 12000 , 43000 这是他们以毫秒为单位的时间,所以这是正确的只是无法正常工作
  • 我也需要 setInterval,因为当时间结束时我会交换它们中的每一个,而不仅仅是设置它们。
  • 你能改变数据吗?而不是不断运行每个条目的间隔,我会向您的数据添加一个属性以跟踪当前显示的记录。像currentlyActive: true 这样的东西。那么您只需要在组件中使用一个“全局”间隔,而不是管理多个间隔
  • 现在完全不可能,如果我想提供另一个属性,我将从我的 rails API 获取数据我的所有数据都将丢失,我需要在不操纵我的数据的情况下管理这个问题

标签: javascript vue.js settimeout setinterval


【解决方案1】:
<template>
  <h1 ...>{{ filteredRecords[index].description }}</h1>
</template>

<script>
{
  data() {
    return {
      index: 0,
      // ...
    };
  },

  methods: {
    iterate(i) {
      if (this.filteredRecords[i]) {
        this.index = i;
        window.setTimeout(() => iterate(i + 1), this.filteredRecords[i].time * 1000);
      }
    },
  },

  mounted() {
    this.iterate(0);
  },
}
</script>

这个怎么样?不使用v-for

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2015-12-04
    • 2016-11-17
    • 2011-07-24
    • 2021-05-10
    • 2017-07-17
    • 2013-03-05
    相关资源
    最近更新 更多