实例生命周期钩子
简单理解,生命周期钩子函数就是vue实例在某一个时间点会自动执行的函数。
<div id="app">{{msg}}</div>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
msg: 'Vue的生命周期'
},
beforeCreate: function() {
console.group('------beforeCreate创建前状态------');
console.log("el : " + this.$el); //undefined
console.log("data : " + this.$data); //undefined
console.log("msg: " + this.msg) //undefined
},
created: function() {
console.group('------created创建完毕状态------');
console.log("el : " + this.$el); //undefined
console.log("data : " + this.$data); //已被初始化
console.log("msg: " + this.msg); //已被初始化
},
beforeMount: function() {
console.group('------beforeMount挂载前状态------');
console.log(this.$el);// <div id="app">{{msg}}</div> 挂载前状态
},
mounted: function() {
console.group('------mounted 挂载结束状态------');
console.log(this.$el);// <div id="app">Vue的生命周期</div> msg内容被挂载并渲染到页面
},
// 当data被修改之前
beforeUpdate: function () {
console.group('beforeUpdate 更新前状态===============》');
console.log("el : " + this.$el);
console.log(this.$el);
console.log("data : " + this.$data);
console.log("msg: " + this.msg);
},
// 触发beforeUpdate之后,虚拟DOM重新渲染并应用更新
// 当data被修改之后
updated: function () {
console.group('updated 更新完成状态===============》');
console.log("el : " + this.$el);
console.log(this.$el);
console.log("data : " + this.$data);
console.log("msg: " + this.msg);
},
// 调用vm.$destroy() 销毁前
beforeDestroy: function () {
console.group('beforeDestroy 销毁前状态===============》');
console.log("el : " + this.$el);
console.log(this.$el);
console.log("data : " + this.$data);
console.log("msg: " + this.msg);
},
// 调用vm.$destroy() 销毁后
destroyed: function () {
console.group('destroyed 销毁完成状态===============》');
console.log("el : " + this.$el);
console.log(this.$el);
console.log("data : " + this.$data);
console.log("msg: " + this.msg)
}
})
</script>
Demo
See the Pen 生命周期钩子 by xugaoyi (@xugaoyi) on CodePen.