Home > Net >  Rewrite Vue component to be more DRY
Rewrite Vue component to be more DRY

Time:04-02

I am just looking for some advice on if there is a more efficient way to write the below, make it a little more DRY?

    <h2>{{ title }}</h2>
    <p>{{ subtitle }}</p>

As I am making the same check for this.name on both title and subtitle I thought there could be a between way than my current implementation, any ideas?

  computed: {
    title() {
      if (this.name === 'discounts_offers') {
        return this.$t('discounts.title')
      }
      if (this.name === 'newsletter') {
        return this.$t('newsletters.title')
      }
      if (this.name === 'product_upgrade') {
        return this.$t('upgrade.title')
      }
      return this.name
   },
    subtitle() {
      if (this.name === 'discounts_offers') {
        return this.$t('discounts.subtitle')
      }
      if (this.name === 'newsletter') {
        return this.$t('newsletters.subtitle')
      }
      if (this.name === 'product_upgrade') {
        return this.$t('upgrade.subtitle')
      }
      return this.name
   },
}

CodePudding user response:

My suggestion :

Literal keys should be same as the value of this.name. So that you can translate them dynamically.

Hence, Instead of multiple if/else clause. You can directly achieve that with a single line of code.

title() {
  return this.$t(this.name)
}

CodePudding user response:

How about something like this?

  data() {
    return {
      map: {
        discounts_offers: "discounts",
        newsletter: "newsletters",
        product_upgrade: "upgrade"
      }
    }
  },
  computed: {
    title() {
      return this.map[this.name] ? this.$t(`${this.map[this.name]}.title`) : this.name
    },
    subtitle() {
      return this.map[this.name] ? this.$t(`${this.map[this.name]}.subtitle`) : this.name
    },
  }

  • Related