mixinを使ってデータをコンポーネント間で共有化する【Vue2】

環境

Vue:2.6.11

内容

mixinを使うことで、export default { } 内に記述するdataやmethodsなどを複数のコンポーネント間で共有することができます。

例えばどのコンポーネントでも使用したいmethodsがあったとして、それぞれのコンポーネントに同じmethodsを記述する必要はなく、mixinに記述することでどのコンポーネントからでも呼び出せるmethodsを設定できます。

sample.vueとsample2.vueのファイルを用意します。

sample.vue

<template>
 <div>
   <p>sample</p>
   <button @click="alert">sampleのテストボタン</button>
   <sample-2> </sample-2>
 </div>
</template>

<script>
import Sample2 from "./sample2.vue";
export default {
 data() {
   return {};
 },
 components: {
   Sample2,
 },
 computed: {},
 methods: {},
};
</script>
<style scoped>
</style>

sample2.vue

<template>
 <div>
   <p>sample2</p>
   <button @click="alert">sample2のテストボタン</button>
 </div>
</template>
 
<script>
export default {
 data() {
   return {};
 },
 computed: {},
 methods: {},
};
</script>
<style scoped>
</style>

画面の状態

どちらもボタンのクリックイベントにalertを紐付けていますが、alertメソッドを実装していないためクリックしても何も起こりません。

では、mixinファイルを作成してalertメソッドを実装してみます。

vueファイルの同階層にalertSample.jsを作成します。

alertSample.jsにalertメソッドを記述します。

alertSample.js

export const alertSample = {
 methods: {
   alert() {
     alert("ボタンがクリックされました");
   },
 },
};

このalertSample.jsをそれぞれのコンポーネントで読み込みます。

import { alertSample } from "./alertSample"; でインポートした後、

mixins: [alertSample] と記述することでmixinファイルをコンポーネントに読み込むことができます。 sample.vue

<template>
 <div>
   <p>sample</p>
   <button @click="alert">sampleのテストボタン</button>
   <sample-2> </sample-2>
 </div>
</template>
 
<script>
import Sample2 from "./sample2.vue";
import { alertSample } from "./alertSample";
export default {
 data() {
   return {};
 },
 components: {
   Sample2,
 },
 mixins: [alertSample],
 computed: {},
 methods: {},
};
</script>
<style scoped>
</style>

sample2.vue

<template>
 <div>
   <p>sample2</p>
   <button @click="alert">sample2のテストボタン</button>
 </div>
</template>
 
<script>
import { alertSample } from "./alertSample";
export default {
 data() {
   return {};
 },
 computed: {},
 mixins: [alertSample],
 methods: {},
};
</script>
<style scoped>
</style>

これでどちらのコンポーネントもalertSample.jsの読み込みが完了しました。

sample.vue、sample2.vueどちらのボタンを教えてもアラートメッセージが表示されます。

sample.vue

sample2.vue