vue的生命周期钩子
beforeCreate
创建前的钩子函数,el还没有挂载,data的数据不存在。
beforeCreate() {
console.log('创建前的钩子函数执行了');
console.log({ "el": this.$el, "data": this.$data, "message": this.msg });
},
created
创建后的钩子函数,data数据已经绑定了,el还没有绑定。一般我们在这个时候进行页面初始化的数据请求,比如axios请求。
created() {
console.log('创建后的钩子函数执行了');
console.log({ "el": this.$el, "data": this.$data, "message": this.msg });
},
beforeMount
挂载前的钩子函数,el绑定,dom节点的数据未解析。
beforeMount() {
console.log('挂载前的钩子函数执行了');
console.log({ "el": this.$el, "data": this.$data, "message": this.msg });
},
mounted
挂载后的钩子函数,el绑定,dom节点的数据渲染已经解析。一般在这里获取页面的dom节点进行操作。
mounted() {
console.log('挂载后的钩子函数执行了');
console.log({ "el": this.$el, "data": this.$data, "message": this.msg });
},
注意事项:
1、组件第一次加载执行,beforeCreate、created、beforeMount、mounted只执行一次。
2、获取数据在那个钩子函数中: created、beforeMount、mounted。
beforeUpdate
更新前的钩子函数,可以执行多次。
beforeUpdate() {
console.log("更新前的钩子运行了");
},
updated
更新后的钩子函数、可以执行多次。
updated() {
console.log("更新后的钩子运行了");
},
beforeDestroy
卸载前的钩子函数、使用app.$destory()可以看到效果。一般用于垃圾回收,定时器、绑定的事件进行解除绑定。
当我们打开页面时在console可以看到
在console中输入app.msg="happy"改变msg的值,更新钩子函数执行。
在console中输入app.$destory(),卸载钩子函数执行
如何定义及使用生命周期钩子函数?
1、钩子函数和data、el、methods是并列的。
存中…(img-S21ltZJm-1621932941048)]
如何定义及使用生命周期钩子函数?
1、钩子函数和data、el、methods是并列的。
2、生命周期钩子的this上下文指向调用它的vue实例。