总的来说,从创建到挂载,是从外到内,再从内到外,且mixins的钩子函数总是在当前组件之前执行。
1、父子组件调用顺序
渲染过程:父beforeCreate-->父created-->父beforeMount-->子beforeCreate-->子created-->子beforeMount-->子mounted-->父mounted;
更新过程:父beforeUpdate-->子beforeUpdate-->子updated-->父updated;
销毁过程:父beforeDestroy-->子beforeDestroy-->子destroyed-->父destroyed;
理解:子组件在父组件内部,所以从父组件开始初始化,中间遇到子组件再进行子组件的渲染和初始化,最后由父组件完成。
2、mixins混入个人感觉可以理解为类的继承,将数据和公共的方法通过export default{}导出,里面内容按照vue语法写data methods created等等内容,,然后在需要的vue文件中引入mixins js文件,引入时同名方法会被vue文件中方法覆盖,不同方法和数据会和vue文件进行合并。
3、示例
demo.html
<body>
<div id="demo">
<child v-init></child>
<button @click="increase">increase</button>
<h2>{{demo}}</h2>
<button @click="destroy">destroy</button>
</div>
<script src="directive.js"></script>
<script src="demo.js"></script>
</body>
directive.js
Vue.directive("init", {
bind: function (el) {
console.log("v-init el is ", el);
}
})
demo.js
let mixin = {
data() {
return {
msg: "mixinMsg",
}
},
beforeCreate() {
console.log("mixin beforeCreate");
},
created() {
console.log("mixin created");
},
beforeMount() {
console.log("mixin beforeMount");
},
mounted() {
console.log("mixin mounted");
},
beforeUpdate() {
console.log("mixin beforeUpdate");
},
updated() {
console.log("mixin updated");
},
methods: {
say() {
console.log("mixin methods say ");
}
}
}
var child = Vue.component("child", {
template: `<h3 @click='sayChild'>child template : {{msg}} {{child}}</h3>`,
name: "child",
mixins: [mixin],
data() {
return {
child: 0
}
},
beforeCreate() {
console.log("child beforeCreate");
},
created() {
console.log("child created");
},
beforeMount() {
console.log("child beforeMount");
},
mounted() {
console.log("child mounted");
},
beforeUpdate() {
console.log("child beforeUpdate");
},
updated() {
console.log("child updated");
},
beforeDestroy() {
console.log("child beforeDestroy");
},
destroyed() {
console.log("child destroyed");
},
methods: {
sayChild() {
this.msg = "childMsg";
this.child++;
console.log("child methods sayDemo child ", this.child);
},
say() {
console.log("child methods say ");
},
}
})
let vm = new Vue({
el: "#demo",
components: { child: child },
data() {
return {
demo: 0
}
},
mixins: [mixin],
beforeCreate() {
console.log("demo beforeCreate");
},
created() {
console.log("demo created");
},
beforeMount() {
console.log("demo beforeMount");
},
mounted() {
console.log("demo mounted");
},
beforeUpdate() {
console.log("demo beforeUpdate");
},
updated() {
console.log("demo updated");
},
beforeDestroy() {
console.log("demo beforeDestroy");
},
destroyed() {
console.log("demo destroyed");
},
methods: {
sayDemo() {
console.log("demo methods sayDemo ");
},
increase() {
this.demo++;
console.log("demo methods increase demo ", this.demo);
},
destroy() {
console.log("demo methods destroy ");
vm.$destroy();
},
}
})
控制台输出
渲染过程:
更新过程:
父组件
子组件
销毁过程:
总结:生命周期遵从“从外到内,再从内到外,mixins先于组件”的原则。