Vue每个生命周期的作用?
Vue.js的生命周期有哪些?每个生命周期都有哪些作用?下面编程教程网小编给大家简单介绍一下!
Vue的生命周期可分为三个阶段:
1.Vue初始化阶段
beforeCreate
:实例刚在内存中被创建出来,未初始化 injections 和 data 等。
created
:实例已经创建完成,data、computed 等都已被初始化好,这时候还未挂载,$el 属性目前不可见。
beforeMount
:模板渲染之前调用,此时 $el 属性还不存在。
mounted
:模板渲染完成,所有子组件也都渲染好了,此时可以通过 DOM API 访问数据。
2.Vue更新阶段
beforeUpdate
:数据更新时调用,发生在虚拟 DOM 打补丁之前。
updated
:有新的虚拟 DOM,在这次更新之后调用。
3.Vue销毁阶段
beforeDestroy
:实例销毁之前调用,这时候实例是完全可用的。
destroyed
:实例销毁后调用,组件相关的所有东西都会被销毁。
Vue生命周期函数的调用顺序:
beforeCreate -> created -> beforeMount ->
mounted -> (beforeUpdate -> updated) * -> beforeDestroy -> destroyed
示列如下:
new Vue({
data() {
return {
msg: 'Hello'
}
},
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')
}
})
以上是编程学习网小编为您介绍的“Vue每个生命周期的作用?”的全面内容,想了解更多关于 vuejs 内容,请继续关注编程基础学习网。