vue.js小技巧之程序化的事件侦听器

本文介绍如何在Vue中使用定时器并确保正确处理组件的生命周期,避免内存泄漏。通过实例展示了在组件挂载时创建定时器,并在组件销毁前清除定时器的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
<!-- 页面挂载时定义计时器,需要在页面销毁时清除定时器
    可以通过 $on 或 $once 监听页面生命周期销毁来解决这个问题:
 -->
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h1>{{ id }}</h1>
    <p>程序化的事件侦听器</p>
  </div>
</template>

<script>
export default {
  name: "SkillFour",
  props: ["id"],
  data() {
    return {
      msg: "vue路由传参参数解耦"
    };
  },
  mounted() {
    this.creatInterval("hello");
    this.creatInterval("world");
  },
  methods: {
    creatInterval(msg) {
      let timer = setInterval(() => {
        console.log(msg);
      }, 1000);
      this.$once("hook:beforeDestroy", function() {
        clearInterval(timer);
      });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style >
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xvzhengyang

感谢,励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值