在vue2.0的时候,声明钩子发生了改变,具体有八个
<!-- HTML部分 --> <div id="app"> <div>{{obj}}</div> <div>{{strings}}</div> <button @click="obj=‘bboz‘">点击</button> </div> <!-- js部分 --> let data = { obj:20 } let vue = new Vue({ el:‘#app‘, data, 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) } });
我们可以看到
关于销毁
app.$destroy();
针对钩子的使用
其实,我们可以把生命钩子当做一个回调函数,只是它是自动的,在特定情况下才回执行的函数
注意:声明周期函数中不能使用 选项属性 和 箭头函数
对此,我们可以想,我们再页面还没创建时候,可以干点什么事情呢?
loading......
当页面销毁前,我们可以给出一个弹框,问是否要确定退出该页面或关闭浏览器等一系列操作等
总结:
生命周期钩子的一些使用方法:
beforecreate : 可以在这加个loading事件,在加载实例时触发
created : 初始化完成时的事件写在这里,如在这结束loading事件,异步请求也适宜在这里调用
mounted : 挂载元素,获取到DOM节点
updated : 如果对数据统一处理,在这里写上相应函数
beforeDestroy : 可以做一个确认停止事件的确认框
nextTick : 更新数据后立即操作dom