父子组件生命周期过程
父子组件的生命周期是一个嵌套的过程
渲染的过程
父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted
子组件更新过程
父beforeUpdate->子beforeUpdate->子updated->父updated
父组件更新过程
父beforeUpdate->父updated
销毁过程
父beforeDestroy->子beforeDestroy->子destroyed->父destroyed
vue项目中的父子组件及组件切换时生命周期顺序
单个组件的生命周期是上面这样的,但是当有父子组件时,是怎样的?
假设有如下两个组件 Home 和 HelloWorld ,HelloWord 是Home的子组件
Home
<template>
<div class="home">
<HelloWorld msg="Welcome to Your Vue.js App" @update="updateParent"/>
<h1>{{data}}</h1>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'home',
data() {
return {data: 'old'}
},
components: {
HelloWorld
},
beforeCreate() {
console.log('父组件 beforeCreate')
},
created() {
console.log('父组件 create')
},
beforeUpdate() {
console.log('父组件 beforeUpdate')
},
updated() {
console.log('父组件 updated')
},
beforeMount() {
console.log('父组件 beforeMount')
},
mounted() {
console.log('父组件 mounted')
},
methods: {
updateParent: function (val) {
this.data = val;
}
}
}
</script>
HelloWorld
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h1>{{ selfMsg }}</h1>
<button @click="changeMsg">点击改状态</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data(){
return {
selfMsg:"hello"
}
},
props: {
msg: String
},
beforeCreate(){
console.log('子组件 beforeCreate')
},
created(){
console.log('子组件 create')
},
beforeUpdate(){
console.log('子组件 beforeUpdate')
},
updated(){
console.log('子组件 updated')
},
beforeMount(){
console.log('子组件 beforeMount')
},
mounted(){
console.log('子组件 mounted')
},
methods:{
changeMsg:function(){
console.log(this);
this.selfMsg = "new msg";
this.$emit('update', 'new');
}
}
}
</script>
更多详细内容,请微信搜索“前端爱好者
“, 戳我 查看 。
情景一:创建
创建的过程是:
父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted
情景二:组件的内部更新
子组件的内部更新过程是:
子beforeUpdate->子updated
同理父组件的内部更新过程也是:
父beforeUpdate->父updated
情景三:子组件修改父组件状态并且父组件绑定该状态到子组件
当子组件使用emit修改父组件状态时,刚好这个状态又绑定在子组件的props上,更新过程是:
父beforeUpdate->子beforeUpdate->子updated->父updated
情景四:父子组件销毁
父组件被销毁时子组件也同时被销毁,销毁的钩子过程是:
父beforeDestroy->子beforeDestroy->子destroyed->父destroyed
情景五:组件切换(如下图:从老页面切换到新页面)
假设从父组件切换到新父组件,新父组件也有子组件,切换的过程生命周期过程是:
新父beforeCreated ->新父created ->新父beforeMount –>新子beforeCreated -> 新子created ->新子beforeMount ->原父beforeDestroy ->原子beforeDestroy –>原子destroyed ->原父destroyed –>新子mounted ->新父mounted
参考文档
- https://zhuanlan.zhihu.com/p/48635981