单个Vue组件的生命周期是按照上图流程进行运转的,但是父子组件之间生命周期钩子函数运行流程又是什么样子的呢?
<!DOCTYPE html>
<html lang="en">
<head> <meta charset="utf-8"> <title>组件事件流测试</title> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> </head>
<body>
<div id="el">这里是父组件{{ name }}<child></child></div>
<div id="event" style="margin-top: 15px;"><div>这里是事件顺序:</div>
<div v-for="(item, index) in events">{{ item }}</div>
</div>
<script>
const events = new Vue({
el: '#event', data: { events: [] },
});
const createHooks = (name) => ({
beforeCreate() { events.events.push(`${name} beforeCreate`); },
created() { events.events.push(`${name} created`); },
beforeMount() { events.events.push(`${name} beforeMount`); },
mounted() { events.events.push(`${name} mounted`); },
});
Vue.component('child', { ...createHooks('child'), template: '<div>这里是子组件<child2 /></div>' });
Vue.component('child2', { ...createHooks('child2'), template: '<div>这里是子子组件</div>' });
var vm = new Vue({
el: '#el', ...createHooks('parent'), data() { return { name: 'parent' }; }
});
</script>
</body>
</html>
运行结果
parent beforeCreate
parent created
parent beforeMount
child beforeCreate
child created
child beforeMount
child2 beforeCreate
child2 created
child2 beforeMount
child2 mounted
child mounted
parent mounted
钩子函数运行顺序