生命周期图示
- 创建前,创建后,挂载前,挂载后,更新前,更新后,销毁前,销毁后
beforeCreate:function(){ console.log('1-beforeCreate 组件还未被创建'); }, created:function(){ console.log('2-created 组件已被创建'); }, beforeMount:function(){ console.log('3-beforeMount 组件已创建但还未挂载到DOM节点上'); }, mounted:function(){ console.log('4-mounted 组件已挂载到DOM节点上'); }, beforeUpdate:function(){ console.log('5-beforeUpdate 数据更新前'); }, updated:function(){ console.log('6-updated 被更新后'); }, activated:function(){ console.log('7-activated'); }, deactivated:function(){ console.log('8-deactivated'); }, beforeDestroy:function(){ console.log('9-beforeDestroy 组件即将被销毁'); }, destroyed:function(){ console.log('10-destroyed 组件已经被销毁') }
<button onclick='app.$destroy()'>销毁</button>
$el、$data
created和mounted
- beforeCreate:el和data并未初始化
- created:完成了data数据的初始化,el没有
- beforeMount: 完成了el和data初始化
mounted: 完成挂载
beforeCreate:function(){ console.log('1-beforeCreate 组件还未被创建'); console.log("%c%s", "color:red" , "el : " + this.$el); //undefined console.log("%c%s", "color:red","data : " + this.$data); //undefined console.log("%c%s", "color:red","message: " + this.message)//undefined }
created:function(){ console.log('2-created 组件已被创建'); console.log("%c%s", "color:red","el : " + this.$el); //undefined console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 }
beforeMount:function(){ console.log('3-beforeMount 组件已创建但还未挂载到DOM节点上'); console.log("%c%s", "color:red","el : " + (this.$el)); //undefined console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 }
- beforeMount 在
.vue文件
中el还没被创建
beforeMount: function () { console.log('beforeMount 挂载前状态===============》'); console.log("%c%s", "color:red","el : " + (this.$el));//已被初始化 console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data);//已被初始化 console.log("%c%s", "color:red","message: " + this.message);//已被初始化 }
- beforeMount在html文件中el已被初始化
mounted:function(){ console.log('4-mounted 组件已挂载到DOM节点上'); console.log("%c%s", "color:red","el : " + this.$el); //已被初始化 console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 }
来源:https://www.cnblogs.com/DCL1314/p/9397320.html