父子组件生命周期执行顺序
加载渲染过程:
父 beforeCreate -> 父 created -> 父 beforeMount -> 子 beforeCreate -> 子 created -> 子 beforeMount -> 子 mounted -> 父 mounted
子组件更新过程: 父 beforeUpdate -> 子 beforeUpdate -> 子 updated -> 父 updated
父组件更新过程: 父 beforeUpdate -> 父 updated
销毁过程: 父 beforeDestroy -> 子 beforeDestroy -> 子 destroyed -> 父 destroyed
总结:
子的生命周期都会被先结束,父的才结束。先由父到子,再从子到父。 生命周期遵从“从外到内,再从内到外,mixins先于组件”的原则。
总的来说,从创建到挂载,是从外到内,再从内到外,且mixins的钩子函数总是在当前组件之前执行
lifestyle.vue
<template>
<div>
<h3 id="dom">子组件Dom 值</h3>
<p id="pppp">子组件message的值是: {{ message }}</p>
<button @click="btnAddMessage">子组件修改message的值</button>
<el-input
type="text"
v-model="value.data"
@change="(v) => changeData('data', v)"
></el-input>
</div>
</template>
<script>
export default {
name:"lifestyle",
data(){
return{
message:"hello,Vue.js"
}
},
props:{
value:[Object]
},
methods:{
btnAddMessage() {
this.amessage += "#";
},
changeData(key,v){
const emitVal={...this.value,[key]:v}
this.$emit('input',emitVal)
},
},
beforeCreate(){
console.log(this.message,"子组件beforeCreate-获取data")
},
created(){
console.log(this.message,"子组件Created-获取data")
},
beforeMount(){
const DEMOH3 = document.querySelector("#dom");
console.log(DEMOH3,"子组件beforeMount-获取dom");
},
mounted(){
const DEMOH3 = document.querySelector("#dom");
console.log(DEMOH3,"子组件Mounted-获取dom");
},
beforeUpdate(){
console.log('子组件beforeUpdate触发了');
},
updated() {
console.log('子组件Update触发了');
},
beforeDestroy(){
console.log('子组件beforeDestroy触发了');
},
destroyed(){
console.log('子组件destroyed触发了');
}
}
</script>
indexl.vue
<template>
<div>
<h3 id="dom">Dom 值</h3>
<p id="pppp">message的值是: {{ message }}</p>
<button @click="btnAddMessage">修改message的值</button>
<lifestyle v-model="input1"></lifestyle> {{ input1 }}
</div>
</template>
<script>
export default {
name:"indexl",
data(){
return{
input1:{data:'212'},
message:"hello,Vue.js",
}
},
methods:{
btnAddMessage() {
this.message += "~";
},
},
beforeCreate(){
console.log(this.message,"beforeCreate-获取data")
},
created(){
console.log(this.message,"Created-获取data")
},
beforeMount(){
const DEMOH3 = document.querySelector("#dom");
console.log(DEMOH3,"beforeMount-获取dom");
},
mounted(){
const DEMOH3 = document.querySelector("#dom");
console.log(DEMOH3,"Mounted-获取dom");
},
beforeUpdate(){
console.log('beforeUpdate触发了');
},
updated() {
console.log('Update触发了');
},
beforeDestroy(){
console.log('beforeDestroy触发了')
},
destroyed(){
console.log('destroyed触发了')
}
}
</script>