vue实现setinterval
Vue 中实现 setInterval 的方法
在 Vue 中,可以使用 setInterval 来执行定时任务,但需要注意在组件销毁时清除定时器以避免内存泄漏。
基本用法
在 Vue 组件的 data 中定义一个定时器变量,并在 mounted 钩子中启动定时器。在 beforeDestroy 钩子中清除定时器。
export default {
data() {
return {
timer: null,
counter: 0
}
},
mounted() {
this.timer = setInterval(() => {
this.counter++
console.log('Counter:', this.counter)
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
使用 Composition API
在 Vue 3 的 Composition API 中,可以使用 onMounted 和 onUnmounted 生命周期钩子来管理定时器。
import { ref, onMounted, onUnmounted } from 'vue'
export default {
setup() {
const counter = ref(0)
let timer = null
onMounted(() => {
timer = setInterval(() => {
counter.value++
console.log('Counter:', counter.value)
}, 1000)
})
onUnmounted(() => {
clearInterval(timer)
})
return {
counter
}
}
}
封装为可复用函数
可以将定时器逻辑封装为一个可复用的函数,方便在多个组件中使用。
import { onUnmounted } from 'vue'
export function useInterval(callback, delay) {
const intervalId = setInterval(callback, delay)
const stop = () => {
clearInterval(intervalId)
}
onUnmounted(stop)
return stop
}
在组件中使用:

import { useInterval } from './useInterval'
export default {
setup() {
const counter = ref(0)
useInterval(() => {
counter.value++
}, 1000)
return {
counter
}
}
}
注意事项
- 确保在组件销毁时清除定时器,避免内存泄漏。
- 在 Composition API 中,定时器的清理逻辑应放在
onUnmounted钩子中。 - 如果需要在定时器中访问组件实例,确保使用箭头函数或正确绑定
this。






