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


在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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM