Appearance
选项式生命周期
1. 父组件
vue3选项式生命周期中,父组件和子组件的生命周期的执行顺序是:
- 初次加载的时候
- 父组件的beforeCreate
- 父组件的created
- 父组件的beforeMount
- 子组件的beforeCreate
- 子组件的created
- 子组件的beforeMount
- 子组件的mounted
- 父组件的mounted
- 更新的时候
- 父组件的beforeUpdate
- 子组件的beforeUpdate
- 子组件的updated
- 父组件的updated
vue
<template>
<div>父组件:</div>
<span>{{ fValue }}</span>
<child v-if="childShow" @update="update" />
<div>
<button @click="childShow = false">隐藏子组件</button>
</div>
</template>
<script>
import child from './child.vue';
export default {
components: {
child,
},
data() {
return {
fValue: '父组件中的值',
childShow: true,
};
},
beforeCreate() {
console.log('beforeCreate---父');
},
created() {
console.log('created---父');
},
beforeMount() {
console.log('beforeMount---父');
},
mounted() {
console.log('mounted---父');
},
beforeUpdate() {
console.log('beforeUpdate---父');
},
updated() {
console.log('updated---父');
},
beforeUnmount() {
console.log('beforeUnmount---父');
},
unmounted() {
console.log('unmounted---父');
},
methods: {
update() {
this.fValue = '父组件中的值被修改了';
},
},
};
</script>2. 子组件
vue
<template>
<div>子组件</div>
{{ cValue }}
<button @click="update">改变</button>
</template>
<script>
export default {
data() {
return {
cValue: '子组件的值',
};
},
beforeCreate() {
console.log('beforeCreate---子');
},
created() {
console.log('created---子');
},
beforeMount() {
console.log('beforeMount---子');
},
mounted() {
console.log('mounted---子');
},
beforeUpdate() {
console.log('beforeUpdate---子');
},
updated() {
console.log('updated---子');
},
beforeUnmount() {
console.log('beforeUnmount---子');
},
unmounted() {
console.log('unmounted---子');
},
methods: {
update() {
this.cValue = '改变后的值';
this.$emit('update');
},
},
};
</script>