混入
混入(mixin)提供了医生非常灵活的方式,来分发 Vue 组件中的可复用功能, 一个混入对象可以包含任意组件选项. 所有混入对象的选项将被”混合”进入该组件本身的选项.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var Mixin - { created() { this.hello() }, methods:{ hello() { console.log('Hi,mixin') } } }
var Component = Vue.extend({ mixins: [myMixin] })
var component = new Component()
|
选项合并
当组件和混入对象含有同名选项时, 这些选项将以恰当的方式进行”合并”
数据对象在内部会进行递归合并, 并在发生冲突时以组件数据优先
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| var mixin = { data() { return { message: 'hello', foo: 'abc' } } } new Vue({ mixin: [mixin], data() { return { message: 'bey', bar: 'def' } }, created() { console.log(this.$data) } })
|
同名钩子函数将合并为一个数组, 因此都将被调用, 混入对象的钩子将在组件自身钩子之前调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var mixin = { created: function() { console.log('混入对象的钩子被调用') } }
new Vue({ mixins: [mixin], created: function() { console.log('组件钩子被调用') } })
|
值为对象的选项,例如 methods、components 和 directives,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| 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() vm.bar() vm.conflicting()
|
全局混入
混入也可以进行全局注册。使用时格外小心!一旦使用全局混入,它将影响每一个之后创建的 Vue 实例。使用恰当时,这可以用来为自定义选项注入处理逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| Vue.mixin({ created: function() { var myOption = this.$options.myOption if (myOption) { console.log(myOption) } } })
new Vue({ myOption: 'hello!' })
|
自定义选项合并策略
自定义选项将使用默认策略,即简单地覆盖已有值。如果想让自定义选项以自定义逻辑合并,可以向 Vue.config.optionMergeStrategies 添加一个函数
1 2 3
| Vue.config.optionMergeStrategies.myOption = function(toVal, fromVal) { }
|
对于多数值为对象的选项,可以使用与 methods 相同的合并策略:
1 2
| var strategies = Vue.config.optionMergeStrategies strategies.myOption = strategies.methods
|
可以在 Vuex 1.x 的混入策略里找到一个更高级的例子:
1 2 3 4 5 6 7 8 9 10
| const merge = Vue.config.optionMergeStrategies.computed Vue.config.optionMergeStrategies.vuex = function(toVal, fromVal) { if (!toVal) return fromVal if (!fromVal) return toVal return { getters: merge(toVal.getters, fromVal.getters), state: merge(toVal.state, fromVal.state), actions: merge(toVal.actions, fromVal.actions) } }
|