用代码来解释生命周期
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/vue/2.1.3/vue.js"></script>
</head>
<body>
<div id="app">
<p>{{ message }}</p>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
message : "Xavier is Zk"
},
beforeCreate: function () {
console.group('beforeCreate ===============');
console.log("%c %s", "color:red" , "el : " + this.$el);
console.log("%c %s", "color:red","data : " + this.$data);
console.log("%c %s", "color:red","message: " + this.message);
console.groupEnd();
},
created: function () {
console.group('created ===============');
console.log("%c %s", "color:red","el : " + this.$el);
console.log("%c %s", "color:red","data : " + this.$data);
console.log("%c %s", "color:red","message: " + this.message);
console.groupEnd();
},
beforeMount: function () {
console.group('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);
console.groupEnd();
},
mounted: function () {
console.group('mounted ===============');
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);
console.groupEnd();
},
beforeUpdate: function () {
console.group('beforeUpdate ===============');
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);
console.groupEnd();
},
updated: function () {
console.group('updated ===============');
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);
console.groupEnd();
},
beforeDestroy: function () {
console.group('beforeDestroy ===============');
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);
console.groupEnd();
},
destroyed: function () {
console.group('destroyed ==============');
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)
console.groupEnd();
}
})
</script>
</body>
</html>
代码运行如下:
再到Console中运行app.message = 'Hello,World',会触发beforeUpdate和updated两个操作
再次到Console中运行app.$destroy(),会触发beforeDestroy和destroyed两个操作
这里再返回来看官方给的生命周期的图,其实挺清楚的,只怪当初自己看不太懂