总结vue2的常用生命周期的作用以及使用方法
时间: 2023-05-19 14:03:10 浏览: 56
Vue2 的常用生命周期有以下几个:
1. beforeCreate:在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用。这个时候,实例上的属性和方法都不能被访问。
2. created:实例已经创建完成之后被调用。在这一步,实例已经完成了数据观测,也就是可以访问到 data、computed、methods 和 watch 等属性和方法。但是,这个时候还没有开始挂载 DOM,所以无法访问到 $el 属性。
3. beforeMount:在挂载开始之前被调用。在这一步,模板已经编译完成,但是还没有开始渲染。
4. mounted:实例挂载之后调用,这个时候 DOM 已经渲染完成,可以访问到 $el 属性。
5. beforeUpdate:数据更新之前被调用,这个时候可以对更新之前的数据进行处理。
6. updated:数据更新之后被调用,这个时候可以对更新之后的数据进行处理。
7. beforeDestroy:实例销毁之前调用。在这一步,实例仍然完全可用。
8. destroyed:实例销毁之后调用,这个时候实例上的所有属性和方法都已经被销毁,无法访问。
使用方法:在 Vue 组件中,可以通过在组件的 options 中定义这些生命周期函数来使用。例如:
```
export default {
data() {
return {
message: 'Hello, Vue!'
}
},
beforeCreate() {
console.log('beforeCreate')
},
created() {
console.log('created')
},
beforeMount() {
console.log('beforeMount')
},
mounted() {
console.log('mounted')
},
beforeUpdate() {
console.log('beforeUpdate')
},
updated() {
console.log('updated')
},
beforeDestroy() {
console.log('beforeDestroy')
},
destroyed() {
console.log('destroyed')
}
}
```
在这个例子中,我们定义了一个组件,并在组件的 options 中定义了所有的生命周期函数。当组件被创建、挂载、更新和销毁时,这些函数会被依次调用。