vue的生命周期想必都不陌生,但是加上子组件,那这个生命周期执行顺序就变成了:
父组件beforeCreate > 父组件created > 父组件beforeMount > 子组件beforeCreate > 子组件created > 子组件beforeMount > 子组件mounted > 父组件mounted > 父组件beforeDestroy > 子组件beforeDestroy > 子组件destroyed > 父组件destroyed
总结一下就是:
父组件在执行到beforeMount之后,子组件会执行到mounted,然后父组件再执行mounted。
销毁的时候,父组件先执行beforeDestroy,然后子组件执行beforeDestroy和destroyed 后,父组件才执行destroyed。
当父组件给子组件传参,进行更新的时候
父组件beforeUpdate > 子组件beforeUpdate > 子组件updated > 父组件updated
以下为代码验证:
父组件:
<template>
<div>
<p>父组件{{currentTime}}</p>
<childCompontent :currentTime="currentTime" />
</div>
</template>
<script>
import childCompontent from "../components/HelloWorld";
export default {
data() {
return {
currentTime: ""
};
},
components: { childCompontent },
beforeCreate() {
console.log("父组件beforeCreate");
},
created() {
console.log("父组件created");
},
beforeMount() {
console.log("父组件beforeMount");
},
mounted() {
this.timer = setInterval(() => {
this.currentTime = new Date().getSeconds();
}, 1000);
console.log("父组件mounted");
},
beforeUpdate() {
console.log("父组件beforeUpdate");
},
updated() {
console.log("父组件updated");
},
beforeDestroy() {
clearInterval(this.timer);
debugger;
console.log("父组件beforeDestroy");
},
destroyed() {
debugger;
console.log("父组件destroyed");
}
};
</script>
子组件:
<template>
<div>
<p>子组件{{currentTime}}</p>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: ["currentTime"],
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() {
debugger;
console.log("子组件beforeDestroy");
},
destroyed() {
debugger;
console.log("子组件destroyed");
}
};
</script>