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

29

标题已经基本解释了,但我想每秒执行一个函数。

我还没有尝试过什么,也没有太多有用的代码。

我已经搜索了一些资料,到目前为止没有找到任何例子可以帮上忙。

此外,我正在使用laravel 5.6

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

export default {
    ready() {
        window.setInterval(() => {
            this.countDown();
        },1000);
    },

1
它为什么会“不工作”?你在何时/何地调用 ready() 函数? - Phil
1
我相信他一定会遇到错误,因为这个问题将会在setInterval回调函数中丢失。你看到控制台中有任何错误吗? - Himanshu Singh
2
没有名为ready的生命周期钩子。https://vuejs.org/v2/api/#Options-Lifecycle-Hooks - Jacob Goh
6个回答

30

为了汇总解决方案(因为我无法编辑),下面的代码可以工作。有一个要点是,您还希望在视图销毁时停止作业,因此您需要在调用beforeDestroy钩子时清除它。

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

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

beforeDestroy() {
  clearInterval(this.timer)
}

这是正确的答案!不需要使用 window 对象。如果不再需要间隔,销毁它也是很好的。 - Sergio Cerrutti
3
在Vue3中,应使用beforeUnmount钩子代替beforeDestroy - vittorio

23

上面发布的答案由于$nextTick的作用每秒都会被触发,因此如果您想设置不同的时间间隔,请删除$nextTick(在我的情况下,我将其设置为30000,因为我需要每30秒触发一次)

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

14

谢谢大家,我找到解决方案了,只需要在谷歌上问对问题就可以了 :)

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

1
为什么要使用 $nextTick?无论如何,您的间隔回调函数都会等待一秒钟才开始执行。 - Phil
1
我没有意识到它的功能是这样的,这是我找到的第一个可行的解决方案。 - The-WebGuy

1
检查一下。这个对我有效。
created() {
    this.interval = setInterval(() => this.getNotifications(), 3000);
}

0
使用Vue3 Composition 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>


0
这种方法最好,因为它确保在组件被销毁之前清除了间隔,而无需在数据中定义任何内容。
created: function() {
  const timer = setInterval(() => {
    this.countDown();
  }, 1000);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接