使用場景:
例如我們在Vue單頁面開發(fā)的時(shí)候當(dāng)多個(gè)組件中都需要下拉刷新,或者使用的都是一個(gè)方法的時(shí)候,我們就可以使用vue mixins進(jìn)行封裝調(diào)用,以及繼承,具體看代碼。
選項(xiàng)合并
var mixin = {
data: function () {
return {
message: 'hello'
}
},
created:function(){
console.log('我是mixins中的created')
},
methods:{
show:function(num){
console.log(num) //mixins種的函數(shù)可以接收組件種的傳參。
},
foo: function () {
console.log('foo')
},
conflicting: function () {
console.log('from mixin')
}
}
}
var vm = new Vue({
mixins: [mixin],
data: function () {
return {
title: 'def',
message: 'goodbye'
}
},
created: function () {
console.log('我是Vue中的created')
console.log(this.$data)
this.show(50); //可通過函數(shù)傳參,把組件中需要的參數(shù)傳給mixins進(jìn)行使用。
},
methods:{
bar: function () {
console.log('bar')
},
conflicting: function () {
console.log('from self')
}
}
})
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"
注意以下三點(diǎn):
1、當(dāng)組件和混入對象含有同名選項(xiàng)時(shí),這些選項(xiàng)將以恰當(dāng)?shù)姆绞交旌稀1热纾瑪?shù)據(jù)對象在內(nèi)部會(huì)進(jìn)行淺合并 (一層屬性深度),在和組件的數(shù)據(jù)發(fā)生沖突時(shí)以組件數(shù)據(jù)優(yōu)先。
2、同名鉤子函數(shù)將混合為一個(gè)數(shù)組,因此都將被調(diào)用。另外,混入對象的鉤子將在組件自身鉤子之前調(diào)用。
3、值為對象的選項(xiàng),例如 methods, components 和 directives,將被混合為同一個(gè)對象。兩個(gè)對象鍵名沖突時(shí),取組件對象的鍵值對。
全局混入
也可以全局注冊混入對象。注意使用! 一旦使用全局混入對象,將會(huì)影響到 所有 之后創(chuàng)建的 Vue 實(shí)例。使用恰當(dāng)時(shí),可以為自定義對象注入處理邏輯。
//為自定義的選項(xiàng) 'myOption' 注入一個(gè)處理器。
Vue.mixin({
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
new Vue({
myOption: 'hello!'
})
// => "hello!"