LoginSignup
20
16

More than 3 years have passed since last update.

v-forの中でcomputedに引数を渡す方法

Last updated at Posted at 2020-10-03

はじめに

タイトル通り「v-forの中の要素でcomputedに引数を渡したい!」と思うことがありましたのでさくっとメモさせて頂きます。
ややサンプルコードが良くない?気がしますが、ご了承くださいませ:bow_tone1:

サンプルコード

Sample.vue
<template>
  <ul>
    <li
      v-for="item in items"
      :key="item.id">
      {{ item.fruit }}:{{ taxPrice(item.price) }}円(税込)
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, fruit: 'りんご', price: 100 },
        { id: 2, fruit: 'みかん', price: 200 },
        { id: 3, fruit: 'ぶどう', price: 300 },
      ],
    }
  },
  computed: {
    taxPrice: function() {
      // 関数の返り値に別の関数を定義し、別の関数内で引数を受け取ってあげる
      return function(itemPrice) {
        return Math.floor(itemPrice * 1.1)
      }
    }
  },
}

コメントアウトにも書かせて頂きましたが、methodsのような記述で引数を受け取ろうとするとうまくいかないので、返り値を関数にして引数を受け取ることができます。

アロー関数式を使う

  computed: {
    taxPrice: () => (itemPrice) => Math.floor(itemPrice * 1.1)
  },

また、ES6から利用できるようになったアロー関数式を使うとスッキリと記述することができます。

おわりに

見てくださった方ありがとうございます!
もし誤字・脱字等ありましたらご指摘頂けると嬉しいです:writing_hand_tone1:
よろしくお願いいたします。

参考文献

Vue.jsでcomputedに引数を渡す方法

20
16
2

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
20
16