vue中实现定时


定时器实现方法
在Vue中实现定时功能通常使用setInterval或setTimeout,结合生命周期钩子管理定时器的创建和销毁。
使用setInterval
export default {
data() {
return {
timer: null,
counter: 0
}
},
mounted() {
this.timer = setInterval(() => {
this.counter++
console.log('定时执行', this.counter)
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
使用setTimeout实现循环
export default {
data() {
return {
counter: 0
}
},
methods: {
startTimer() {
setTimeout(() => {
this.counter++
console.log('延迟执行', this.counter)
this.startTimer() // 递归调用实现循环
}, 1000)
}
},
mounted() {
this.startTimer()
}
}
使用Vue的$once自动清理
export default {
mounted() {
const timer = setInterval(() => {
console.log('定时任务')
}, 1000)
this.$once('hook:beforeDestroy', () => {
clearInterval(timer)
})
}
}
使用Composition API
import { onMounted, onUnmounted, ref } from 'vue'
export default {
setup() {
const counter = ref(0)
let timer = null
onMounted(() => {
timer = setInterval(() => {
counter.value++
}, 1000)
})
onUnmounted(() => {
clearInterval(timer)
})
return { counter }
}
}
注意事项
定时器需要在组件销毁时清除,避免内存泄漏
对于需要响应式更新的数据,确保使用Vue的响应式系统(data或ref)
复杂场景可考虑使用专门的定时任务库如node-cron






