混入 (mixins) 是一種分發 Vue 組件中可復用功能的非常靈活的方式。混入對象可以包含任意組件選項。當組件使用混入對象時,所有混入對象的選項將被混入該組件本身的選項。
- 數據對象合並
數據對象在內部會進行淺合並 (一層屬性深度),在和組件的數據發生沖突時以組件數據優先
var mixin = { data() { return { msg_mixins: 'mixins', msg: '123' } } } var app = new Vue({ mixins: [mixin], el: '#app', data: { msg: 'app' } })
- 鈎子函數合並
同名鈎子函數將混合為一個數組,因此都將被調用。另外,混入對象的鈎子將在組件自身鈎子之前調用。
var mixin = { data() { return { msg_mixins: 'mixins', msg: '123' } }, created: function () { console.log('混入對象的鈎子被調用') } } var app = new Vue({ mixins: [mixin], el: '#app', data: { msg: 'app' }, created: function () { console.log('組件鈎子被調用') } })

混入鈎子函數.png
- methods, components 和 directives合並
methods, components 和 directives,將被混合為同一個對象。兩個對象鍵名沖突時,取組件對象的鍵值對。
var mixin = { data() { return { msg_mixins: 'mixins', msg: '123' } }, created: function () { console.log('混入對象的鈎子被調用') }, methods: { foo: function () { console.log('foo') }, conflicting: function () { console.log('from mixin') } } } var app = new Vue({ mixins: [mixin], el: '#app', data: { msg: 'app' }, created: function () { console.log('組件鈎子被調用') }, methods: { bar: function () { console.log('bar') }, conflicting: function () { console.log('from self') } } })

方法混合.png
- 全局混入
一旦使用全局混入對象,將會影響到 所有 之后創建的 Vue 實例。
Vue.mixin({ created: function () { console.log('全局混入') } })
