vue实现setinterval计数
Vue 中使用 setInterval 实现计数功能
在 Vue 中实现计数功能可以通过 setInterval 定时器来实现,但需要注意 Vue 的响应式特性和内存管理。以下是具体实现方法:
基本实现方式
在 Vue 组件的 data 中定义一个计数器变量,在 mounted 钩子中启动定时器:
export default {
data() {
return {
count: 0,
timer: null
}
},
mounted() {
this.timer = setInterval(() => {
this.count++
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
使用 Composition API
如果使用 Vue 3 的 Composition API,可以通过 setup 函数实现:

import { ref, onMounted, onBeforeUnmount } from 'vue'
export default {
setup() {
const count = ref(0)
let timer = null
onMounted(() => {
timer = setInterval(() => {
count.value++
}, 1000)
})
onBeforeUnmount(() => {
clearInterval(timer)
})
return {
count
}
}
}
封装为可复用组件
可以将计数器逻辑封装为可复用组件:
// Counter.vue
export default {
props: {
interval: {
type: Number,
default: 1000
}
},
data() {
return {
count: 0,
timer: null
}
},
methods: {
start() {
this.timer = setInterval(() => {
this.count++
}, this.interval)
},
stop() {
clearInterval(this.timer)
}
},
mounted() {
this.start()
},
beforeDestroy() {
this.stop()
}
}
注意事项
定时器需要在组件销毁时清除,避免内存泄漏

对于需要暂停和继续的场景,可以添加相应的方法控制
在服务端渲染(SSR)场景下,mounted 钩子不会执行,需要特殊处理
带暂停和继续功能的实现
export default {
data() {
return {
count: 0,
timer: null,
isRunning: false
}
},
methods: {
start() {
if (!this.isRunning) {
this.isRunning = true
this.timer = setInterval(() => {
this.count++
}, 1000)
}
},
pause() {
this.isRunning = false
clearInterval(this.timer)
},
reset() {
this.pause()
this.count = 0
}
},
mounted() {
this.start()
},
beforeDestroy() {
this.pause()
}
}
以上实现方式涵盖了 Vue 中 setInterval 计数的基本用法和常见场景,可以根据实际需求选择合适的方案。






