在Vue项目中使用clearTimeout的最佳实践是在组件销毁时清除定时器。具体做法如下:
示例代码如下:
export default { data() { return { timerId: null } }, mounted() { this.startTimer() }, methods: { startTimer() { this.timerId = setTimeout(() => { // 执行定时任务 }, 1000) } }, beforeDestroy() { clearTimeout(this.timerId) } } 通过以上做法,可以确保在组件销毁时清除定时器,避免内存泄漏和不必要的性能开销。