LoginSignup
0
0

More than 1 year has passed since last update.

Vue.jsのMixinがあれば可読性が上がり変更に強くなるかも

Posted at

ミックスインとは?

ミックスイン (mixin) は、Vue コンポーネントに再利用可能で柔軟性のある機能を持たせるための方法です。

ミックスインを使っていなかった場合

商品一覧画面で商品名と価格を表示するVueコンポーネント例

Index.vue
<template>
  <div>
    <div v-for="item in items" :key="item">
      <p>{{ item.name }}</p>
      <p>{{ calculateWithTax(item.price) }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        {
          name: 'ポテト',
          price: 200
        },
        {
          name: 'ハンバーガー',
          price: 500
        },
        {
          name: 'コカコーラ',
          price: 150
        }
      ]
    }
  },
  methods: {
    calculateWithTax(price) {
      const taxRate = 10
      const tax = price * taxRate
      return price + tax
    }
  }
}
</script>

ひとつの商品の詳細を表示するVueコンポーネント例

ItemDetail.vue
<template>
  <div>
      <p>{{ item.name }}</p>
      <p>{{ calculateWithTax(item.price) }}</p>
      <p>{{ item.description }}</p>
      <p>{{ item.ingredients }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      item: {
        name: 'ハンバーガー',
        price: 500,
        description: 'マクドナルドのハンバーガー。ピクルスとケチャップ入り',
        ingredients: 'パン(国産)、牛肉(アメリカ産)、きゅうり(国産)、トマトケチャップ(アメリカ産)'
      }
    }
  },
  methods: {
    calculateWithTax(price) {
      const taxRate = 10
      const tax = price * taxRate
      return price + tax
    }
  }
}
</script>

このようにシンプルな商品一覧画面と商品詳細画面を作ったとします。
現在の消費税が10%なので各商品を表示する際に販売価格(price)に対して消費税を加えるメソッドを通して返ってきた値を表示しなければなりません。
消費税というのは悲しくも数年から数十年に一度変動する値なのでもし改正がきたらプログラムも変えなければ正しい値をユーザーに届けてあげられません。

ではもし10%が5%に改正されたらどうでしょう?(消費税を減らしてほしいという筆者の願望)
※プログラムを修正する前に一旦ガッツポーズ

Index.vueとItemDetail.vueのcalculateWithTaxメソッドにあるtaxRateという定数を変更してあげなければなりません。
まあ2ファイルならすぐ変えられますね!

ただこんなシンプルなプログラムは少ないと思うので実際に稼働しているサービスでは数10ファイルあるかもしれません。さらにはチーム開発によってtaxRateという定数ではなく色々な名前で定義されているというパターンもなきにしもあらずでそうなってくると変更が大変になってしまいます。

ここで使えるのが今回紹介するミックスインです!

冒頭に公式ドキュメントからの引用がある通り、ミックスインは、Vueコンポーネントに再利用可能で柔軟性のある機能を持たせるための方法というものですので、今回の消費税を加える実装も再利用可能な状態を作ってあげることができます。

それでは実際に利用してみます。

ミックスインを使った場合

まずは早速ミックスインのjsファイルを用意します。
以下のようにdataとmethodsを定義しexportします。

mixin.js
export default {
  data () {
    return {
      taxRate: 10
    }
  },
  methods: {
    calculateWithTax(price) {
      const tax = price * this.taxRate
      return price + tax
    }
  }
}

先ほど用意したmixin.jsをimportしてmixinに定義してあげます。

Index.vue
<template>
  <div>
    <div v-for="item in items" :key="item">
      <p>{{ item.name }}</p>
      <p>{{ calculateWithTax(item.price) }}</p>
    </div>
  </div>
</template>

<script>
import mixin from './mixin'

export default {
  mixins: [mixin],
  data() {
    return {
      items: [
        {
          name: 'ポテト',
          price: 200
        },
        {
          name: 'ハンバーガー',
          price: 500
        },
        {
          name: 'コカコーラ',
          price: 150
        }
      ]
    }
  }
}
</script>

同じく詳細画面にもimportして定義する

ItemDetail.vue
<template>
  <div>
      <p>{{ item.name }}</p>
      <p>{{ calculateWithTax(item.price) }}</p>
      <p>{{ item.description }}</p>
      <p>{{ item.ingredients }}</p>
  </div>
</template>

<script>
import mixin from './mixin'

export default {
  mixins: [mixin],
  data() {
    return {
      item: {
        name: 'ハンバーガー',
        price: 500,
        description: 'マクドナルドのハンバーガー。ピクルスとケチャップ入り',
        ingredients: 'パン(国産)、牛肉(アメリカ産)、きゅうり(国産)、トマトケチャップ(アメリカ産)'
      }
    }
  }
}
</script>

これだけでメソッドを共通化して各々のファイル内で呼び出してあげればミックスインで定義しておいたメソッドが使えるようになります。
これでもし消費税が変わったらmixin.jsをいじってあげるだけで消費税+価格を表示していた各所に反映されますね!

今回はdataとmethodsがミックスインに移すことに成功しましたが、他にもcreatedやcomputed、templateまでミックスインに定義することができるのでVueファイル内で再利用可能な箇所はここに整理してあげると可読性も変更にも強くなりそうですね。

最後に

いかがだったでしょうか?
今回はミックスインについて紹介させていただきました。
詳細につきましては以下の公式ドキュメントにてご確認お願いいたします。
ミックスイン - Vue.js

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