Vue中在組件銷毀時清除定時器(setInterval)


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

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