14. Mixins

Mixins

基本

Mixin是一种为Vue组件分配可重用功能的灵活方式。mixin对象可以包含任何组件选项。当一个组件使用mixin时,mixin中的所有选项将被“混合”到组件自己的选项中。

例:

// define a mixin object var myMixin = { created: function () { this.hello() }, methods: { hello: function () { console.log('hello from mixin!') } } } // define a component that uses this mixin var Component = Vue.extend{ mixins: [myMixin] }) var component = new Component() // => "hello from mixin!"

选项合并

当mixin和组件本身包含重叠选项时,它们将使用适当的策略进行“合并”。例如,具有相同名称的钩子函数会合并到一个数组中,以便所有这些函数都会被调用。另外,mixin钩子将在组件钩之前被调用:

var mixin = { created: function () { console.log('mixin hook called') } } new Vue{ mixins: [mixin], created: function () { console.log('component hook called') } }) // => "mixin hook called" // => "component hook called"

那些期望对象的值,例如选项methodscomponents并且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"

请注意,在Vue.extend()中使用了相同的合并策略。

Global Mixin

您也可以在全局范围内应用混合。谨慎使用!一旦您在全局范围内应用混合,它将影响之后创建的每个 Vue实例。正确使用时,可以使用它来为自定义选项注入处理逻辑:

// inject a handler for `myOption` custom option Vue.mixin{ created: function () { var myOption = this.$options.myOption if (myOption) { console.log(myOption) } } }) new Vue{ myOption: 'hello!' }) // => "hello!"

稀疏而谨慎地使用全局混合,因为它会影响每个创建的Vue实例,包括第三方组件。在大多数情况下,您只应将其用于自定义选项处理,如上例所示。将它们作为插件发布以避免重复应用也是一个好主意。

自定义选项合并策略

自定义选项合并后,它们将使用覆盖现有值的默认策略。如果您想要使用自定义逻辑来合并自定义选项,则需要附加一个函数以Vue.config.optionMergeStrategies

Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) { // return mergedVal }

对于大多数基于对象的选项,您可以使用以下相同的且被methods使用的策略:

var strategies = Vue.config.optionMergeStrategies strategies.myOption = strategies.methods

更高级的例子可以在Vuex1.x的合并策略中找到:

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) } }