Vue.jsの見落とされがちな機能は、コンポーネントの構成です。 アプリ全体で再利用可能な機能を提供するために、最小限の労力で1つ以上のコンポーネントを拡張および継承できます。

拡張機能は、別のコンポーネントのオプションをコンポーネントとマージすることで機能します。 重複するプロパティはコンポーネントによって上書きされ、重複するメソッドが次々に呼び出されます。

延長

拡張を使用すると、他の1つのコンポーネントを拡張でき、コンポーネントのオプションが親コンポーネントのオプションよりも優先されます。 これは、たとえば、親とコンポーネントの両方に created()フックが含まれている場合、コンポーネントの created()フックが最初に呼び出され、次に親のフックが呼び出されることを意味します。

ParentComponent.vue
<script>
export default {
  created() {
    console.log('Created from the parent!');
  }
}
</script>
ChildComponent.vue
<script>
import ParentComponent from './ParentComponent.vue';

export default {
  extends: ParentComponent,

  created() {
    console.log('Created from the child!');
  }
}
</script>

出力:

Created from the child!
Created from the parent!

Mixins

Mixinはさらにクールです。 これらを使用すると、複数コンポーネント定義を拡張できます。 ミックスインを使用すると、任意の数のコンポーネントに再利用可能なメソッドとデータを簡単に提供できます。

唯一の大きな違いは、コンポーネント自体のフックの前に、ミックスインフックが順番に呼び出されることです。

my-mixins.js
export const mixin1 = {
  created() {
    console.log('Created Mixin 1');
  }
}

export const mixin2 = {
  created() {
    console.log('Created Mixin 2');
  }
}

export const mixin3 = {
  mounted() {
    console.log('Mounted Mixin 3');
  }
}

export const mixin4 = {
  mounted() {
    console.log('Mounted Mixin 4');
  }
}
ChildComponent.vue
<script>
import {mixin1, mixin2, mixin3, mixin4} from './my-mixins.js';

export default {
  mixins: [mixin1, mixin2, mixin3, mixin4],

  created() {
    console.log('Created from the child!');
  },

  mounted() {
    console.log('Mounted from the child!');
  }
}
</script>

出力:

Created Mixin 1
Created Mixin 2
Created from the child!

Mounted Mixin 3
Mounted Mixin 4
Mounted from the child!

グローバルミックスイン

ミックスインはグローバルに登録することもでき、その機能をすべてのVueコンポーネントに注入します。 これはロギングやデバッグに役立つ場合がありますが、通常はプラグインの外部では使用されません。 注意してください。グローバルミックスインは、サードパーティのコンポーネントを含め、アプリ内のすべてのコンポーネントの機能を変更するため、何をしているのか明確に理解していない限り、一般的にそれらを使用することはお勧めできません。

グローバルミックスインを作成するには、Vue.mixinに登録します。

import Vue from 'vue';

Vue.mixin({
  created() {
    // Will be called every time a component is created.
    console.log('Mixin created!');
  }
})