效果:
native message
您的代办事项有:3 件
控制台输出:
created in overrall
created in aaa
created in native
mounted in overrall
mounted in aaa
mounted in native
点击+按钮,控制台输出:
addItem in native
可见,混入的生命周期钩子事件执行顺序是:先全局混入,再局部混入,最后构造器。
混入的data和methods将被构造器覆盖。
代码:
<h1>Mixins-混入属性和方法等到构造器内部</h1>
<div id="app2">
{{ message }}
<p>您的代办事项有:{{ count }} 件 <button @click="addItem"> + </button></p>
</div>
<script>
//全局混入 用于权限校验或调研用户习惯 慎用
Vue.mixin({
data:function () {
return {
message:"overrall message"
}
},
created:function () {
console.log("created in overrall");
},
mounted:function () {
console.log("mounted in overrall");
}
});
//局部混入 常用于开发阶段的测试
var aaa={
data:{
message:"aaa message"
},
methods:{
addItem:function () {
console.log("addItem in aaa");
}
},
created:function () {
console.log("created in aaa");
},
mounted:function () {
console.log("mounted in aaa");
}
};
var vm = new Vue({
el:"#app2",
data:{
message:"native message",
count:3
},
methods:{
addItem:function () {
console.log("addItem in native");
}
},
created:function () {
console.log("created in native");
},
mounted:function () {
console.log("mounted in native");
},
mixins:[aaa]
});
</script>
版权声明:本文为xuanwuziyou原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。