iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 26
2
自我挑戰組

vue.js 30天學習軌跡系列 第 26

Day26 vue.js - 使用mixin將多個組件混入

mixin

Mixins是為Vue組件分發可重用功能的靈活方法。
mixin對象可以包含任何組件選項(生命週期、data、computed、 methods...)。
當組件使用mixin時,mixin中的所有選項都將被混入到組件自己的選項中。

局部註冊

// mixin object
var mixinTwo = {
  created: function () {
    this.hi()
  },
  methods: {
    hi: function () {
      console.log('hi from mixinTwo!')
    }
  }
}
var mixinOne = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixinOne!')
    }
  }
}

new Vue({
  mixins: [mixinOne,mixinTwo],
})

全域註冊

但使用上需要非常的謹慎,因為它會影響每個單獨創建的Vue實例
建議將其作為插件發布,以避免重複應用混入。

Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})
new Vue({
  myOption: 'hello!'
})

選項合併

當組件和mixin對象含有同名選項時,這些選項將以恰當的方式進行合併

demo1

data對像在內部會進行遞歸合併,並在發生衝突時以則Vue 實例優先級會較高

var mixin = {
  data: function () {
    return {
      message: 'mixin 你好!',
      foods: '薯條'
    }
  }
}
new Vue({
  mixins: [mixin],
  data: {    
    message: 'vue實例 你好!',
    drink: '可樂'
  },
  created: function () {
    console.log(this.$data)
  }
})

demo2

同名Hook函數將合併為一個數組,因此都將被調用。
另外,mixin對象的Hook將在組件自身Hook之前調用。

var mixin = {
  created: function () {
    console.log('我來自mixin')
  }
}

new Vue({
  mixins: [mixin],
  created: function () {
    console.log('我來自組件')
  }
})

補充 mixins 與 exten 差異
mixins : 可加入多個元件
extends : 只能擴展單個元件
/images/emoticon/emoticon08.gif


上一篇
Day25 vue.js - 使用$set寫入資料
下一篇
Day27 vue.js - 自定義指令 Custom Directive
系列文
vue.js 30天學習軌跡30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言