<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>总结生命周期</title> <script type="text/javascript" src="../vue.js"></script> </head> <body> <div id="root"> <h2 v-if="isShowHello">你好</h2> <h2 :style="{opacity}">欢迎学习Vue</h2> <button @click="opacity = 1">透明度设置为1</button> <button @click="stop">停止变换</button> </div> <script type="text/javascript"> Vue.config.productionTip = false // 组织开发环境提示 // 创建Vue实例 const vm = new Vue({ el: '#root', data: { isShowHello: true, opacity: 1 }, methods: { stop() { this.$destroy() } }, // Vue完成模板解析,并把真实的DOM放入页面后调用mounted注意这里是方法函数,不是对象,刷新页面不会调用mounted mounted() { console.log('mounted') this.timer = setInterval(() => { console.log("setInterval") this.opacity -= 0.01 if (this.opacity <= 0) this.opacity = 1 }, 16) }, beforeDestroy() { console.log("beforeDestroy-清除定时器") clearInterval(this.timer) } }) // setInterval(()=>{ // vm.opacity -= 0.01 // if (vm.opacity <= 0) vm.opacity = 1 // },16) </script> </body> </html>