Vue.js 2.0 混合

2022-01-28 15:32 更新

Vue.js 2.0 混合基礎(chǔ)

混合是一種靈活的分布式復(fù)用 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!"

選項合并

當(dāng)組件和混合對象含有同名選項時,這些選項將以恰當(dāng)?shù)姆绞交旌稀1热?,同名鉤子函數(shù)將混合為一個數(shù)組,因此都將被調(diào)用。另外,混合對象的 鉤子將在組件自身鉤子之前調(diào)用 :

var mixin = {
  created: function () {
    console.log('mixin hook called')
  }
}
new Vue({
  mixins: [mixin],
  created: function () {
    console.log('component hook called')
  }
})
// -> "混合對象的鉤子被調(diào)用"
// -> "組件鉤子被調(diào)用"

值為對象的選項,例如 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"

注意: Vue.extend() 也使用同樣的策略進(jìn)行合并。

全局混合

也可以全局注冊混合對象。 注意使用! 一旦使用全局混合對象,將會影響到所有之后創(chuàng)建的 Vue 實例。使用恰當(dāng)時,可以為自定義對象注入處理邏輯。

// 為自定義的選項 'myOption' 注入一個處理器。 
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})
new Vue({
  myOption: 'hello!'
})
// -> "hello!"

謹(jǐn)慎使用全局混合對象,因為會影響到每個單獨創(chuàng)建的 Vue 實例(包括第三方模板)。大多數(shù)情況下,只應(yīng)當(dāng)應(yīng)用于自定義選項,就像上面示例一樣。 也可以將其用作插件以避免產(chǎn)生重復(fù)應(yīng)用。

自定義選項混合策略

自定義選項將使用默認(rèn)策略,即簡單地覆蓋已有值。 如果想讓自定義選項以自定義邏輯混合,可以向 Vue.config.optionMergeStrategies 添加一個函數(shù):

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

對于大多數(shù)對象選項,可以使用 methods 的合并策略:

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

更多高級的例子可以在 Vuex 1.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)
  }
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號