Home > database >  How to concatenate a key in JSON response coming from API and display in VUE component
How to concatenate a key in JSON response coming from API and display in VUE component

Time:11-27

I need to concatenate a json key for displaying the contents based on the current language selected. In API I am getting the response and current language selected. The response is like below

{
  lang : "en"
  heading_ar: "قابل وتناول واستمتع بالاختبار الحقيقي"
  heading_en: "Meet, Eat & Enjoy the true test"
  description_ar: "<p>هناك حقيقة مثبتة منذ زمن طويل وهي أن المحتوى المقروء لصفحة</p>"
  description_en: "<p>It is a long established fact that a</p>"
  id: 1
}

in template I should display the contents. But I cannot able to concatenate lang in heading . I tried different ways but nothing is working.

<template>
<h1 class="banner-title">{{banner.home.heading_ banner.home.lang}}</h1>
</template>

thank you

CodePudding user response:

<template>
<h1 class="banner-title">{{banner.home.heading_en}}{{banner.home.lang}}</h1>
</template>

EDIT: after clarifying requirements

<template>
    <h1 class="banner-title">{{computedHeading}}</h1>
</template>

and to your script add computed property

computed: {
// a computed getter
  computedHeading: function () {
    if(this.banner.home.lang == "en"){
      return this.banner.home.heading_en
    }else{
      return this.banner.home.heading_ar
    } 
}

}

EDIT: after OP said he has many languages optimisation

Note that this does not need to be computed property, if your data is not changing only set this once

computed: {
// a computed getter
  computedHeading: function () {
        let prefix = "heading_"
        let headingPath = prefix this.banner.home.lang
        return this.banner.home[headingPath]
  }
}

CodePudding user response:

With string interpolation {{`${banner.home.heading_} some text ${banner.home.lang}`}}
  • Related