钩子函数
- 钩子函数(Hook)在Vue中是一种事件劫持机制。
- 它会比定义的事件更早进行执行处理,而且可以让你自己去配置。
钩子 | 描述 |
---|---|
beforeCreate | 实例创建前状态 el与data都为 undefined |
created | 创建完毕状态 el为undefined,data里面已经有数据 |
beforeMount | 挂载前状态 el:undefined data里面已有数据 |
mounted | 挂载后状态 el与data都有相对应的属性 |
beforeUpdate | 更新前状态 data里面的属性值改变el:[object HTMLDivElement] |
updated | 更新完成状态 data里面的属性值改变 el:[object HTMLDivElement] |
beforeDestroy | 销毁前状态 |
destroyed | 销毁状态 |
总结:数据请求一般写在created里面,第三方库如果要用的话一般往mounted里写。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
</head>
<body>
<div id="app"></div>
<script>
let app = new Vue({
el: "#app",
data: {
msg: "hello world"
},
template: "<div>{{msg}}</div>",
beforeCreate() {
console.log("beforeCreate", this.$el, 'data=', this.msg)
setTimeout(() => {this.msg = 'msg更新'}, 1000)
},
created() {
console.log("created", this.$el, 'data=', this.msg)
},
beforeMount() {
console.log("beforeMount", this.$el, 'data=', this.msg)
},
mounted() {
console.log("mounted", this.$el, 'data=', this.msg)
},
beforeDestroy() {
console.log("beforeDestroy", this.$el, 'data=', this.msg)
},
destroyed() {
console.log("destroyed", this.$el, 'data=', this.msg)
},
beforeUpdate() {
console.log("beforeUpdate", this.$el, 'data=', this.msg)
},
updated() {
console.log("updated", this.$el, 'data=', this.msg)
}
})
</script>
</body>
</html>
理解生命周期
- beforeCreate和created钩子函数之间的生命周期
这个生命周期之间,进行初始化事件,进行数据的观测, created的时候数据已经和data属性进行绑定。 - created钩子函数和 beforeMount间的生命周期
首先会判断对象是否有el选项。如有,继续向下编译,如无,则停止编译,也就意味着停止了生命周期,直到在该vue实例上调用wm.$mount(el)。 - beforeMount和mounted钩子函数间的生命周期
给νue实例对象添加$el成员,并且替换掉挂载的DOM元素。 - mounted
在mounted之前页面数据是通过占位符占位的, mounted之后占位符内容发生更新。 - beforeUpdate和 updated钩子函数间的生命周期
当vue发现data中的数据发生了改变,会触发对应组件的重新渲染,先后调用beforeUpdate和 updated钩子函数。 - beforeDestroy和 destroyed钩子函数间的生命周期
beforeDestroy钩子函数在实例销毁之前调用,实例仍然完全可用。
destroyed钩子函数在Vue实例销毁后调用。调用后,Vue实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。