例子:數組
// 定義一個混入對象 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!"
好比,數據對象在內部會進行遞歸合併,在和組件的數據發生衝突時以組件數據優先。函數
var mixin = { data: function () { return { message: 'hello', foo: 'abc' } } } new Vue({ mixins: [mixin], data: function () { return { message: 'goodbye', bar: 'def' } }, created: function () { console.log(this.$data) // => { message: "goodbye", foo: "abc", bar: "def" } } })
var mixin = { created: function () { console.log('混入對象的鉤子被調用') } } new Vue({ mixins: [mixin], created: function () { console.log('組件鉤子被調用') } }) // => "混入對象的鉤子被調用" // => "組件鉤子被調用"
methods
, components
和 directives
,將被混合爲同一個對象。兩個對象鍵名衝突時,取組件對象的鍵值對。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() // => "from self"