3.总结生命周期.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>引出生命周期</title>
  8. <!-- 引入vue -->
  9. <script type="text/javascript" src="../js/vue.js"></script>
  10. </head>
  11. <body>
  12. <!--
  13. 常用的生命周期钩子:
  14. 1、mounted:发送Ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作】
  15. 2、beforeDestroy:清除定时器、解绑自定义事件、取消订阅消息等【收尾工作】
  16. 关于销毁Vue实例
  17. 1、销毁胡借助Vue开发者工具看不到任何信息
  18. 2、销毁后自定义事件会失效,但原生DOM事件依然有效
  19. 3、一般不会再beforeDestroy操作数据,因为即使操作数据,也不会再触发更新流程了。
  20. -->
  21. <!-- 准备一个容器 -->
  22. <div id="root">
  23. <h2 :style="{opacity}">欢迎学习Vue</h2>
  24. <button @click="opacity=1">透明度设置为1</button>
  25. <button @click="stop">点我停止变换</button>
  26. </div>
  27. </body>
  28. <script>
  29. Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示
  30. new Vue({
  31. el: '#root',
  32. data: {
  33. opacity: 1
  34. },
  35. methods: {
  36. stop(){
  37. // clearInterval(this.timer)
  38. this.$destroy()
  39. }
  40. },
  41. // Vue完成模板的解析并把初始的真实的DOM元素放入页面后(挂载完毕)调用mounted
  42. mounted() {
  43. console.log('mounted',this)
  44. this.timer = setInterval(() => {
  45. this.opacity -= 0.01
  46. if(this.opacity <= 0) this.opacity = 1
  47. }, 16);
  48. },
  49. beforeDestroy() {
  50. console.log('vm即将销毁')
  51. clearInterval(this.timer)
  52. },
  53. })
  54. </script>
  55. </html>