LoginSignup
0
0

More than 5 years have passed since last update.

【Vue】mixin オプションを別の mixin で使用する方法

Posted at

Vue.util.mergeOptionsを使う

Vue.util モジュールには多数のユーティリティメソッドを持っています。
その中に mergeOption メソッドがあり、 これを利用して mixin 同士のオプションをマージさせます👆
※本来は vue インスタンスオプションをマージするために利用されます。

サンプル



const mixin1 = {
  data () {
    return {
      mixin1: 'aaa'
    }
  },
  methods: {
    method1 () {
      console.log('method 1')
    }
  }
}
// Vue.util.mergeOptionsで mixin1 と mixin2 をマージする
const mixin2 = Vue.util.mergeOptions(mixin1, {
  data () {
    return {
      mixin2: 'bbb'
    }
  },
  methods: {
    method2 () {
      console.log('method 2')
    }
  }
})
const mixin3 = {
  mixins: [mixin2],
  data () {
    return {
      mixin3: 'ccc'
    }
  },
  methods: {
    method3 () {
      console.log('method 3')
    },
    methodAll () {
      this.method1()
      this.method2()
      this.method3()
    }
  }
}

new Vue({
  el: '#app',
  mixins: [mixin3],
  data () {
    return {
      message: 'hello'
    }
  },
  created () {
    this.methodAll()
  }
})

// => "method 1"
// => "method 2"
// => "method 3"

上記の場合、 data オプションの中身は以下のようになります。

data
{
  "message": "hello",
  "mixin3": "ccc",
  "mixin2": "bbb",
  "mixin1": "aaa"
}

Vue.util.mergeOptions を使用することで、
他の mixin が持っているメソッドをコピーしなくても、
それらのコンポーネント内で利用することが可能になります👏

注意点

mixin とコンポーネント自体に、重複するオプションが含まれる場合

たとえば、 created などのライフサイクルフックは配列にマージされ、すべてが呼び出されます✅
※コンポーネントよりも先に、 mixin のライフサイクルフックが実行されます

methods などのオプションが重複するとコンポーネントのオプションにオーバライドされます✅
※同じ methods名やdataプロパティ名など、マージしている場合は常に上書きされます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0