9_生命周期.html 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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>Document</title>
  8. </head>
  9. <body>
  10. <div id="app">
  11. <button @click="fn()">+1</button>
  12. <button @click="des()">销毁</button>
  13. <h2 id="myCount">{{count}}</h2>
  14. </div>
  15. <script src="vue.js"></script>
  16. <script>
  17. new Vue({
  18. el:'#app',
  19. data:{
  20. count: 1
  21. },
  22. methods:{
  23. fn(){
  24. this.count++
  25. },
  26. des(){
  27. this.$destroy()
  28. }
  29. },
  30. //组件实例刚刚创建的时候 属性计算之前
  31. beforeCreate(){
  32. console.log('beforeCreate',this.$data,this.$el)
  33. },
  34. //组件实例刚刚创建完成,属性绑定了,dom未生成,el不存在
  35. created(){
  36. console.log('created',this.$data,this.$el)
  37. },
  38. //挂载之前
  39. beforeMount(){
  40. console.log('beforeMount',this.$data,this.$el)
  41. },
  42. //挂载之后
  43. mounted(){
  44. console.log('mounted',this.$data,this.$el)
  45. this.timer = setInterval(()=>{
  46. console.log(Math.random())
  47. this.count++
  48. },1000)
  49. },
  50. //更新之前
  51. beforeUpdate(){
  52. console.log('beforeUpdate',document.getElementById('myCount').innerHTML)
  53. },
  54. //更新之后
  55. updated(){
  56. console.log('updated',document.getElementById('myCount').innerHTML)
  57. },
  58. //销毁前
  59. beforeDestroy(){
  60. console.log('beforeDestroy')
  61. clearInterval(this.timer)
  62. },
  63. //销毁后
  64. destroyed(){
  65. console.log('destroyed')
  66. }
  67. /*
  68. beforeCreate: 在实例初始化之后,数据和event/watcher事件配置之前去调用
  69. created: 在实例创建完成后立即被调用,这个阶段可以访问到实例的数据和方法,但是没有挂载到dom上
  70. beforeMount:在挂载开始前被调用,在这个阶段,模板的编译已经完成,但是还是没有将组件挂载到Dom上
  71. mounted:在挂载完成后被调用,此时组件已经被挂载到dom上,可以进行dom操作或者访问组件的Dom元素
  72. beforeUpdate:在数据更新之前被调用,发生在dom重新渲染之前,可以在这个阶段进行状态的修改
  73. updated:在数据更新之后被调用,发生在dom重新渲染之后,可以执行一些依赖更新后的dom操作
  74. beforeDestroy:在实例销毁之前被调用,可以进行一些清理工作,比如清除定时器
  75. destroyed:在实例销毁后被调用,组件已经完全销毁,所有的事件监听器和子组件被移除。
  76. */
  77. })
  78. </script>
  79. </body>
  80. </html>