Vue中在组件销毁时清除定时器(setInterval)

本文介绍在Vue项目中如何正确地使用定时器。在组件挂载(mounted)时创建并执行定时器,当组件即将销毁(beforeDestroy)时清除定时器,确保避免内存泄漏。文章通过具体代码展示了这一过程。
在mounted中创建并执行定时器,然后在beforeDestroy或者destroyed中清除定时器
<template>
      <div class="about">
      </div>
    </template>
    <script>
    export default {
        name: "about",
        data() {
            return {
                //接收定时器
                timer: ""
            };
        },
        mounted() {
            let _this = this;
            let num = 0;
            //创建并执行定时器
            this.timer = setInterval(() => {
              //当num等于100时清除定时器
                if (num == 100) {
                    clearInterval(_this.timer);
                }
                console.log(num++);
            }, 1000);
        },
        beforeDestroy() {
            //清除定时器
            clearInterval(this.timer);
            console.log("beforeDestroy");
        },
        destroyed() {
            //清除定时器
            //clearInterval(this.timer);
            console.log("destroyed");
        }
    };
    </script>
    <style scoped>
    </style>

转载于:https://www.cnblogs.com/web-chuanfa/p/10857007.html

参考资源链接:[Vue显示当前组件](https://wenku.youkuaiyun.com/doc/2oyzbtjzhj?utm_source=wenku_answer2doc_content)Vue项目中实现一个实更新的当前间显示功能,可以通过结合组件的生命周期钩子、数据绑定以及定时器来完成。以下是详细步骤和代码示例: 1. **定义Vue组件**:首先,你需要定义一个Vue组件,其中包含初始化数据、模板以及自定义过滤器。 ```javascript new Vue({ el: '#app', data: { timeDate: new Date() }, filters: { formatDate(value) { const date = new Date(value); return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`; } }, methods: { updateTime() { this.timeDate = new Date(); } }, mounted() { this.timer = setInterval(this.updateTime, 1000); }, beforeDestroy() { clearInterval(this.timer); } }); ``` 在这个示例中,`data`函数返回一个包含`timeDate`属性的对象,它用来存储当前间。`filters`定义了一个`formatDate`过滤器,用于将`timeDate`格式化为易读的字符串格式。 2. **模板绑定和定时器设置**:在模板中,使用`{{timeDate | formatDate}}`来绑定显示格式化后的间。通过`mounted`生命周期钩子设置一个每秒更新间的定时器。在`beforeDestroy`钩子中清除定时器,这是为了避免内存泄漏。 3. **组件销毁的内存管理**:通过在`beforeDestroy`钩子中使用`clearInterval`方法来清除定时器,确保当Vue实例被销毁定时器会继续执行,从而防止内存泄漏。 以上步骤结合了Vue的生命周期管理、数据绑定以及JavaScript定时器操作,实现了在Vue组件中实显示并更新当前间的功能,同组件销毁避免了潜在的内存问题。如果你希望进一步了解间处理和Vue组件生命周期的相关知识,可以参考《Vue显示当前组件》这份资料,它详细解析了相关知识点,并提供了实战代码示例。 参考资源链接:[Vue显示当前组件](https://wenku.youkuaiyun.com/doc/2oyzbtjzhj?utm_source=wenku_answer2doc_content)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值