现有如下结构代码。
app.vue
globalMixin.js
--home.vue
----Ch6.vue
----mixin.js
-------Ch7.vue
//以上组件都会执行自身钩子函数,在home中混入mixin代码
首先我们对相关组件钩子函数有一定了解。学习地址
全局App.vue
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
import globalMixin from '@/mixin/globalMixin'
export default {
mixins: [globalMixin],
beforeCreate() {
console.log("app beforeCreate");
},
created() {
console.log("app created");
},
beforeMount() {
console.log('app beforeMount');
},
mounted() {
console.log("app mounted");
}
}
</script>
混入代码(mixin.js)
export default {
data() {
return {
msg: "我是minx中的数据"
}
},
beforeCreate() {
console.log("mixin中的beforeCreate");
},
created() {
console.log("mixin中的created");
},
beforeMount() {
console.log("mixin中的beforeMount");
},
mounted() {
console.log("mixin中的mounted");
}
}
混入代码(globalMixin.js)
export default {
data() {
return {
msg: "我是globalMixin中的数据"
}
},
beforeCreate() {
console.log("globalMixin中的beforeCreate");
},
created() {
console.log("globalMixin中的created");
},
beforeMount() {
console.log("globalMixin中的beforeMount");
},
mounted() {
console.log("globalMixin中的mounted");
}
}
混入代码(Home.vue) 路由匹配器出口
其中嵌入ch-6子组件,ch-6组件内嵌ch-7组件
<template>
<!-- 探究 vue文件 minx 嵌套组件 生命周期执行的顺序 -->
<div class="home">
<ch-6 />
</div>
</template>
<script>
import mixin from '@/mixin/mixin'
import ch6 from '@/components/ch-6/ch-6'
export default {
name: "Home",
mixins: [mixin],
components: {
ch6
},
data() {
return {}
},
beforeCreate() {
console.log('Home beforeCreate');
},
created() {
console.log('Home created');
},
mounted() {
console.log('Home mounted');
},
methods: {}
};
</script>
Ch6子组件,内嵌Ch7孙子组件
<template>
<div>
<p>ch6组件</p>
<ch-7 />
</div>
</template>
<script>
import ch7 from '@/components/ch-7/ch-7'
export default {
name: "Ch-6",
components: {
"ch-7": ch7
},
beforeCreate() {
console.log('ch-6 beforeCreate');
},
created() {
console.log('ch-6 create');
},
beforeMount() {
console.log('ch-6 beforeMount');
},
mounted() {
console.log('ch-6 mounted');
}
}
</script>
Ch7孙子组件
<template>
<p>ch7组件</p>
</template>
<script>
export default {
name: "Ch-7",
beforeCreate() {
console.log('ch-7 beforeCreate');
},
created() {
console.log('ch-7 create');
},
beforeMount() {
console.log('ch-7 beforeMount');
},
mounted() {
console.log('ch-7 mounted');
}
}
</script>
控制台输出结果
总结:
混入代码的生命周期钩子高于组件生命周期钩子,再执行app的beforeCreate、created 和 beforeMount,然后再去执行Home组件的beforeCreate、created 和 beforeMount,最后去执行子组件的beforeCreate、created 和 beforeMount,如果子组件下面没有子组件了,就执行 mounted,然后再返回父级执行 mounted。可以简单理解为进栈出栈,minx>app>components,mounted若想要被执行,一定是页面dom结构被完成渲染完成。所以组件的mounted必然比父组件先执行。