vue 销毁定时器的写法
时间: 2023-08-16 17:15:09 浏览: 60
在 Vue 中销毁定时器的写法可以通过两种方式来实现:
方式一:使用 `clearInterval()` 或 `clearTimeout()` 方法来清除定时器。
在 Vue 组件中,可以在 `beforeDestroy` 或 `destroyed` 钩子函数中调用 `clearInterval()` 或 `clearTimeout()` 来清除定时器。例如:
```javascript
export default {
data() {
return {
timer: null
};
},
mounted() {
this.timer = setInterval(() => {
// 定时器的回调函数
}, 1000);
},
beforeDestroy() {
clearInterval(this.timer);
}
}
```
方式二:使用 Vue 的 `$destroy` 方法销毁组件,同时会清除所有定时器。
在 Vue 组件中,可以通过调用 `$destroy` 方法来销毁组件,从而清除所有的定时器。例如:
```javascript
export default {
mounted() {
this.timer = setInterval(() => {
// 定时器的回调函数
}, 1000);
},
methods: {
destroyComponent() {
this.$destroy();
}
}
}
```
需要注意的是,使用 `$destroy` 方法销毁组件会触发组件的生命周期钩子函数,所以需要根据实际情况决定在哪个钩子函数中进行其他操作。