LoginSignup
0
0

More than 3 years have passed since last update.

備忘録 vue.js computed、filters使い方

Posted at
<template>
  <div>
    <p v-for='item in items' :key = 'item.name'>
      {{ item.name }}
      {{ item.price | numberWithDelimiter}}
      {{ item.quantity }}
    </p>
    <p>合計金額(税抜き) {{ totalPrice }} </p>
    <p>合計金額(税込み) {{ totalPriceWithTax }} </p>
  </div>
</template>

<script>
export default { 
  name: 'Section2',
  data: function() {
    return {
      items:[
            {
              name: 'pencil',
              price: 1300,
              quantity: 1,
            },
            {
              name: 'note',
              price: 1400,
              quantity: 2,
            },
            {
              name: 'eraser',
              price: 1300,
              quantity: 3,
            }
      ]
    }
  },
  computed: {
    totalPrice: function() {
      var sum = 0;
      for(var i = 0; i < this.items.length; i++) {
        sum += this.items[i].price * this.items[i].quantity;
      }
      return sum;
    },
    totalPriceWithTax: function() {
      var sum = 0;
      for(var i = 0; i < this.items.length; i++) {
        sum += this.items[i].price * this.items[i].quantity;
      }
      return Math.floor(sum * 1.10);
    }
  },

  filters: {
    numberWithDelimiter: function(value){
      if(!value){
        return 0;
      } else{
        return value.toLocaleString();
      }
    }
  },
}
</script>

<style scoped>
</style>

※数字にカンマ付けする場合は、正規表現でも可能だが、toLocaleString()を使用する事で3桁カンマ付けにできる。

※filtersを使用するときはムスタッシュ記号内で{{ ○○ | △△ }}と書くことで文字列を整形してクライアントに表示できる。

参考:Vue.js入門 基礎から実践アプリケーション開発まで 技術評論社 https://gihyo.jp/book/2018/978-4-297-10091-9

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