混入是一種分發Vue組件中可複用功能很是靈活的方式。混入對象能夠包含任意組件選項。當組件使用混入對象時,全部混入對象的選項將被混入該組件自己的選項。
例子:函數
//定義一個混入對象 var myMixin={ created:function(){ this.hello(); }, methods:{ hello:function(){ console.log('hello from mixin'); } } } //定義一個使用混入對象的組件 var Component = Vue.extend({ mixins:[myMixin] }) var component = new Component();=>hello from mixin
當組件和混入對象含有同名選項時,這些選項將以恰當的方式混合。
好比,數據對象在內部會進行遞歸合併,在和組件的數據發生衝突時以組件數據優先。this
var mixin ={ data:function(){ return{ messageL:'hello', foo:'abc' } }, created(){ console.log('混入對象的鉤子被調用') } } new Vue({ mixins:[mixin], data:function(){ return{ message:'goodbye', bar:'def } }, created:function(){ console.log('組件鉤子被調用') console.log(this.$data); // => { message: "goodbye", foo: "abc", bar: "def" } } })
值爲對象的選項,例如methods,components和directives,將被混合爲同一個對象。兩個對象鍵名衝突時,取組件對象的鍵值對。code
var mixin={ methods:{ foo:function(){ console.log('foo') }, conflicting:function(){ console.log('from mixin') } } } var vm = new Vue({ mixins:[mixin], methods:{ bar:function(){ console.log('bar') }, conflicting:function(){ console.log('from self') } } }) vm.foo()//foo vm.bar()//bar vm.conflicting()//form self
也能夠全局註冊混入對象。注意使用!一旦使用全局混入對象,將會影響到全部以後建立的Vue實例。使用恰當時,能夠爲自定義對象注入處理邏輯。component
//爲自定義的選項myOption注入一個處理器。 Vue.mixin({ creted:function(){ var myOption = this.$options.myOption; if(myOption){ console.log(myOption) } } }) new Vue({ myOption:'hello' })
謹慎使用全局混入對象,由於會影響到每一個單首創建Vue實例(包括第三方模板)。大多數狀況下,只應當應用於自定義選項,就像上面示例同樣。也能夠將其用做Plugins以免產生重複做用。orm
自定義選項將使用默認策略,即簡單的覆蓋已有值。若是想讓自定義選項以自定義邏輯合併,能夠向Vue.config.optionMergeStrategies添加一個函數:對象
Vue.config.optionMergeStrategies.myOption=function(toVal,fromVal){ return mergedVal }
對於大多數對象選項,能夠使用methods的合併策略:遞歸
var strategies = Vue.config.optionMergeStrategies; strategies.myOption = strategies.methods