Vue3 没有默认每秒运行的功能,但可以通过 setInterval() 或者 requestAnimationFrame() 方法来实现每秒运行的效果。

以下是 setInterval() 方法的示例代码:

<template>
  <div>
    <p>{{ counter }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      counter: 0
    }
  },
  mounted() {
    setInterval(() => {
      this.counter++
    }, 1000)
  }
}
</script>

以上代码会每秒钟增加计数器的值。

以下是 requestAnimationFrame() 方法的示例代码:

<template>
  <div>
    <p>{{ counter }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      counter: 0
    }
  },
  mounted() {
    this.loop()
  },
  methods: {
    loop() {
      this.counter++
      requestAnimationFrame(this.loop)
    }
  }
}
</script>

以上代码会每秒钟增加计数器的值,但是它的运行方式与 setInterval() 方法不同,因为 requestAnimationFrame() 方法会根据浏览器的刷新频率来调用函数,因此它的运行速度可以更加平滑。

vue3 每秒运行

原文地址: https://www.cveoy.top/t/topic/f0a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录