mixins 将两个的对象的混合为一个数组,彼此都可以被调用,下面为演示代码及其结果
ps:当对象键值对 键名冲突时,保留非mixin对象的键值对
<div id="app"></div>
<script>
var myMixin={
template:'<h1>holle mixin</h1>',
methods:{
hello:function(){
console.log('this is mixin')
},
say:function(){
console.log('I am mixin')
}
}
};
var Component=Vue.extend({
mixins:[myMixin],
methods:{
lsit:function(){
console.log('I am lsit')
},
say:function(){
console.log('I am not mixin say')
}
}
});
var newcom=new Component().$mount('#app')
newcom.hello();
newcom.lsit();
newcom.say();
</script>
全局的混合
<div id="app"></div>
<script>
Vue.mixin({
created:function(){
this.hello()
},
methods:{
hello:function(){
console.log('this is mixin')
},
say:function(){
console.log('I am mixin')
}
}
});
var app=new Vue({
el:"#app",
methods:{
lsit:function(){
console.log('I am lsit')
},
say:function(){
console.log('I am mixin say')
}
}
});
app.hello();
app.lsit();
app.say();
</script>
比如项目中多处的view层使用到下拉刷新以及自动加载功能,处理这些相同的逻辑,每一个view层都要写一遍是浪费生命的。这种情况就很适合使用mixin。