Vue实例的生命周期_两个重要的钩子
作者:互联网
饮水思源:
https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks
https://www.bilibili.com/video/BV1Zy4y1K7SH?p=49&spm_id_from=pageDriver
引入生命周期——一个渐变特效
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title></title> <script src="JS/vue.js"></script> </head> <body> <h1>一个渐变特效&VUE的生命周期</h1> <div id="root"> <h2 :style="{opacity}">一个渐变的文字</h2> </div> <script> new Vue({ el: "#root", data: { opacity: 0.5 }, mounted() { console.log("mount是挂载的意思,mounted是挂载完毕,也就是dom被放入页面后"); setInterval(() => { this.opacity -= 0.01; if (this.opacity <= 0) this.opacity = 1; }, 20) }, }); </script> </body> </html>
两个重要的钩子——mounted和beforeDestroy
单纯stop,组件确实不再更新,但是计时器没有关掉,也就是“setInterval没被干掉”还会不断输出:
<script> new Vue({ el: "#root", data: { opacity: 0.5, }, methods: { stop() { this.$destroy(); } }, mounted() { this.tid = setInterval(() => { console.log("setInterval没被干掉") this.opacity -= 0.01; if (this.opacity <= 0) this.opacity = 1; }, 20) }, }); </script>
正确的写法,在销毁之前还需要处理后事,并且这个逻辑应该写在自己身上:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title></title> <script src="JS/vue.js"></script> </head> <body> <h1>一个渐变特效&VUE的生命周期</h1> <div id="root"> <h2 :style="{opacity}">一个渐变的文字</h2> <button v-on:click="stop">点我停止渐变</button> </div> <script> new Vue({ el: "#root", data: { opacity: 0.5, }, methods: { stop() { this.$destroy(); } }, mounted() { this.tid = setInterval(() => { console.log("setInterval没被干掉") this.opacity -= 0.01; if (this.opacity <= 0) this.opacity = 1; }, 20) }, beforeDestroy() { clearInterval(this.tid) }, }); </script> </body> </html>
标签:opacity,生命周期,setInterval,钩子,渐变,Vue,mounted 来源: https://www.cnblogs.com/xkxf/p/15843333.html