Vue js 每 x 秒触发一个方法/函数

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

标题几乎解释了它,但我希望每秒触发一个函数。

我没有尝试过任何东西,也没有太多有用的代码。

我已经做了一些谷歌搜索,到目前为止,我对任何例子都感到高兴。

另外,我正在使用 laravel 5.6

这不起作用,无法调用 countDown() 方法

export default {
    ready() {
        window.setInterval(() => {
            this.countDown();
        },1000);
    },
vuejs2 laravel-5.6
6个回答
29
投票

为了结合解决方案(因为我无法编辑),下面的代码可以工作。一个问题是,您还希望在视图被销毁后停止作业,因此您需要在调用

beforeDestroy
钩子时清除它

mounted: function () {
  this.timer = setInterval(() => {
    this.countDown()
  }, 1000)
},

data() {
  return {
    timer: null
  }
},

beforeDestroy() {
  clearInterval(this.timer)
}

23
投票

上面发布的答案每秒触发一次(因为 $nextTick),所以如果您想设置不同的间隔,只需删除 $nextTick (在我的例子中,我将其设置为 30000,因为我必须每 30 秒触发一次)

mounted: function () {
  window.setInterval(() => {
    this.getNotifications()
  }, 30000)
}

14
投票

谢谢大家,我找到了解决方案,只是在谷歌上问了一些正确的问题:)

mounted: function () {
        this.$nextTick(function () {
            window.setInterval(() => {
                this.countDown();
            },1000);
        })
    }

1
投票

看看这个。这个对我有用。

created() {
    this.interval = setInterval(() => this.getNotifications(), 3000);
}

0
投票

这效果最好,因为它可以确保在组件被销毁之前清除间隔,而无需在数据中定义任何内容。

created: function() {
  const timer = setInterval(() => {
    this.countDown();
  }, 1000);

  this.$once("hook:beforeDestroy", () => {
    clearInterval(timer);
  });
} 

0
投票

使用 Vue3 组合 API

<script setup>
import { onMounted, onBeforeUnmount, ref } from "vue";

const timer = ref();

function countDownFunc() {
console.log("Running countDownFunc")
...
}

// Instantiate
onMounted(() => {
  timer.value = setInterval(() => {
    countDownFunc();
  }, 3000);
});

// Clean up
onBeforeUnmount(() => {
  timer.value = null;
});

</script>

© www.soinside.com 2019 - 2024. All rights reserved.