生命周期探究
对于执行顺序和什么时候执行,看上面两个图基本有个了解了。下面我们将结合代码去看看钩子函数的执行。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <script type="text/javascript" src="https://cdn.jsdelivr.net/vue/2.1.3/vue.js"></script> 6 </head> 7 <body> 8 9 <div id="app"> 10 <p>{{ message }}</p> 11 </div> 12 13 <script type="text/javascript"> 14 15 var app = new Vue({ 16 el: '#app', 17 data: { 18 message : "" 19 }, 20 beforeCreate: function () { 21 console.group('beforeCreate 创建前状态===============》'); 22 console.log("%c%s", "color:red" , "el : " + this.$el); //undefined 23 console.log("%c%s", "color:red","data : " + this.$data); //undefined 24 console.log("%c%s", "color:red","message: " + this.message) 25 }, 26 created: function () { 27 console.group('created 创建完毕状态===============》'); 28 console.log("%c%s", "color:red","el : " + this.$el); //undefined 29 console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 30 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 31 }, 32 beforeMount: function () { 33 console.group('beforeMount 挂载前状态===============》'); 34 console.log("%c%s", "color:red","el : " + (this.$el)); //已被初始化 35 console.log(this.$el); 36 console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 37 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 38 }, 39 mounted: function () { 40 console.group('mounted 挂载结束状态===============》'); 41 console.log("%c%s", "color:red","el : " + this.$el); //已被初始化 42 console.log(this.$el); 43 console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 44 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 45 }, 46 beforeUpdate: function () { 47 console.group('beforeUpdate 更新前状态===============》'); 48 console.log("%c%s", "color:red","el : " + this.$el); 49 console.log(this.$el); 50 console.log("%c%s", "color:red","data : " + this.$data); 51 console.log("%c%s", "color:red","message: " + this.message); 52 }, 53 updated: function () { 54 console.group('updated 更新完成状态===============》'); 55 console.log("%c%s", "color:red","el : " + this.$el); 56 console.log(this.$el); 57 console.log("%c%s", "color:red","data : " + this.$data); 58 console.log("%c%s", "color:red","message: " + this.message); 59 }, 60 beforeDestroy: function () { 61 console.group('beforeDestroy 销毁前状态===============》'); 62 console.log("%c%s", "color:red","el : " + this.$el); 63 console.log(this.$el); 64 console.log("%c%s", "color:red","data : " + this.$data); 65 console.log("%c%s", "color:red","message: " + this.message); 66 }, 67 destroyed: function () { 68 console.group('destroyed 销毁完成状态===============》'); 69 console.log("%c%s", "color:red","el : " + this.$el); 70 console.log(this.$el); 71 console.log("%c%s", "color:red","data : " + this.$data); 72 console.log("%c%s", "color:red","message: " + this.message) 73 } 74 }) 75 </script> 76 </body> 77 </html>
beforecreate
: 举个栗子:可以在这加个loading事件 created
:在这结束loading,还做一些初始化,实现函数自执行 mounted
: 在这发起后端请求,拿回数据,配合路由钩子做一些事情beforeDestory
: 你确认删除XX吗? destoryed :当前组件已被删除,清空相关内容