我对 webpack 的最初信仰就是,它非常的智能化,可以将一切的资源(包括html css javascirpt image)用 import 和 require 模块化引入,并对资源进行预处理,最终被打包成一个js文件解释执行。
接下来我想谈谈vue的生命周期和钩子函数。
每个 Vue 实例在被创建之前都要经过一系列的初始化过程。例如需要设置数据监听、编译模板、挂载实例到 DOM、在数据变化时更新 DOM 等。
说的直白一点,分别对应的四组钩子函数就是:
beforeCreate 、created; // 创建前、创建完成
beforeMount 、mounted;// 挂载前、挂载完成
beforeUpdate 、updated; // 更新前、更新完成
beforeDestory 、destoryed。// 销毁前、销毁完成
这里闰土在网上找到一个很好的例子:
<!DOCTYPE html>
<html>
<head>
<title>Vue生命周期</title>
<script type="text/javascript" src="http://cdn.jsdelivr.net/vue/2.1.3/vue.js"></script>
</head>
<body>
<div>
<p>{{ message }}</p>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
message : "闰土少年"
},
beforeCreate: function () {
console.group('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)
},
created: function () {
console.group('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.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); //已被初始化
},
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); //已被初始化
},
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);
},
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);
},
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);
},
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)
}
})
</script>
</body>
</html>
最后在chrome的console控制台打印效果如下图: