上次博客写了Vue的生命周期,这次我们谈一谈父子组件中的生命周期。
首先我创建了父子组件,父组件APP,子组件Child,他们之间通过props传递数据,父组件中有一个按钮,当点击按钮时页面中的某些数据会发生改变,这个按钮的作用主要就是用来监测updated和beforeUpdate的这两个钩子函数在父子组件中的执行顺序。
父子组件生命周期过程:
上图就是父子组件的生命周期。
接下来我对这一结果进行一个分析:
这是父组件的部分代码,我们将name以Props的形式将它传入子组件中。
1.mounted之前的钩子函数执行顺序
因为我们在main.js中引入了APP组件,因此程序执行时首先进入父组件APP,先进入beforeCreate和created,因为这两个阶段只是进行初始化和数据代理,并不知道自身引用了子组件Child,所以不会进入子组件。只有当父组件开始挂载(beforeCreate)时,他才开始解析页面,这时才会发现页面中引用了Child组件,于是它直接进入Child组件开始解析,进入Child组件后,同父组件执行流程一样,先是beforeCreate和created,然后执行beforeMount和mounted,当挂在完毕之后紧接着执行父组件的下一条语句,当父组件的所有语句执行完成之后,就进入了mounted。因此执行流程为 父组件beforeCreate----->父组件created------>父组件beforeMount----->子组件beforeCreate----->子组件created----->子组件beforeMount----->子组件mounted---->父组件mounted。
2.beforeUpdate和updeted执行顺序
在本例中(代码会在最后附上),当点击按钮后name数据会改变,当数据改变时这两个钩子函数会被触发。
在点击按钮时,他首先触发了父组件中数据的变化,因此需要重新进行编译,发现使用了子组件Child,因此进入子组件,将子组件的数据更新完再开始执行父组件的下一条语句,最后数据更新完毕updeted。因此执行流程为 父组件beforeUpdate----->子组件beforeUpdate----->子组件updeted----->父组件updeted。
3.beforeDestroy和destroyed
销毁其实和更新是一个道理,在点击按钮时,他首先触发了父组件中数据的beforeDestroy,在准备销毁时发现还有子组件Child,因此进入子组件,将子组件的数据销毁完再开始执行父组件的下一条语句,最后数据更新完毕updeted。因此执行流程为 父组件beforeDestroy----->子组件beforeDestroy----->子组件destroyed----->父组件destroyed。
页面截图:
代码:
父组件APP
<template> <div> <Child :name="name"/> <button @click='update'>更改信息</button> <button @click='destroy'>销毁信息</button> </div> </template> <script> import Child from './Child.vue' export default { name:'App', data() { return { name:'雪球' } }, components:{Child}, methods: { update(){ this.name='胖雪球' }, destroy(){ this.$destroy() } }, 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"); } } </script> <style> button{ margin-left: 20px; } </style>
子组件Child:
<template> <div> <h2 >我叫:{{name}}</h2> </div> </template> <script> export default { name:"Child", props:["name"], 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"); } } </script> <style> </style>
综上就是我对父子组件生命周期执行顺序的理解,如有不正确的地方欢迎大家指正。