shin_moto
@shin_moto

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Vue.jsでcomputedのリファクタリング

Discussion

Closed

解決したいこと

コードをリファクタリングしたいと考えています。
Vue.js v2.6.10

例)

<template>
<!-- 略 -->
<div v-if="selectedTypeFee1">
   <div>{{ $t('金額') }}</div>
   <div>{{ selectedTypeFee1 }}</div>
</div>

<div v-if="selectedTypeFee2">
   <div>{{ $t('金額') }}</div>
   <div>{{ selectedTypeFee2 }}</div>
</div>

<div v-if="selectedTypeFee3">
   <div>{{ $t('金額') }}</div>
   <div>{{ selectedTypeFee3 }}</div>
</div>
<!-- 略 -->
</template>

<script>
// 略
computed: {
  selectedTypeFee1() {
    if (this.$props.type == TYPE_1) {
      let fee = this.tyep1Fee;
        if (!this.isEmpty(fee)) { // isEmpty()は空判定をするメソッドと仮定
          return Number(fee);
        }
    }
    return 0;
  },

  selectedTypeFee2() {
    if (this.$props.type == TYPE_2) {
      let fee = this.tyep2Fee;
        if (!this.isEmpty(fee)) {
          return Number(fee);
        }
    }
    return 0;
  },

  selectedTypeFee3() {
    if (this.$props.type == TYPE_3) {
      let fee = this.tyep3Fee;
        if (!this.isEmpty(fee)) {
          return Number(fee);
        }
    }
    return 0;
  },

タイプ1~3を同時に表示することはありません。
どれも表示しないことはありますが、表示する場合もどれか1つだけを表示します。

今後タイプのバリエーションが増える度にテンプレートも書かないといけないのが冗長なので、もう少しスッキリ書く事が出来ればと考えています。アドバイス頂けると助かります。

0
<div v-if="selectedTypeFee">
   <div>{{ $t('金額') }}</div>
   <div>{{ selectedTypeFee }}</div>
</div>
selectedTypeFee() {
  let fee;
  switch (this.$props.type) {
    case TYPE_1:
      fee = this.tyep1Fee;
      break;

    ...
  }

  return ...;
},

のようにできそうではありますね。

1Like

力技ですが、以下でいけそうな気がします。

selectedTypeFee() {
  return Number(this[`${this.$props.type.replace("_", "").toLowerCase()}Fee`] || 0);
}

※tyep1Fee=>type1Feeに修正する必要あり

this.$props.type"TYPE_1"等が入っている前提で上は書いているのでreplaceとかtoLowerCaseとかは必要に合わせて調整してください。

1Like

@woxtu さん
お返事遅れて申し訳ありません、ご意見感謝します。
switch文でスッキリ書く事が出来ました^^

@h_kono0707 さん
お返事遅れて申し訳ありません、アドバイスありがとう御座います。
勉強になります。

0Like

Your answer might help someone💌