【问题标题】:How to concatenate a key in JSON response coming from API and display in VUE component如何连接来自 API 的 JSON 响应中的键并在 VUE 组件中显示
【发布时间】:2022-01-05 00:53:03
【问题描述】:

我需要连接一个 json 键来根据当前选择的语言显示内容。在 API 中,我正在选择响应和当前语言。响应如下

{
  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
}

在模板中我应该显示内容。但我无法在heading 中连接lang。我尝试了不同的方法,但没有任何效果。

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

谢谢

【问题讨论】:

    标签: javascript laravel vue.js inertiajs


    【解决方案1】:
    <template>
    <h1 class="banner-title">{{banner.home.heading_en}}{{banner.home.lang}}</h1>
    </template>
    

    编辑:明确要求后

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

    在你的脚本中添加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
        } 
    }
    

    }

    编辑:在 OP 说他有很多语言优化之后

    请注意,这不需要计算属性,如果您的数据没有更改,只需设置一次

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

    【讨论】:

    • 这将如何工作?我想显示 heading_en 或 heading_ar 而不是同时显示
    • 这不是你的问题,我也会进行编辑以帮助你解决这个问题
    • 我需要连接json键。基于此,我应该取值
    • 计算属性工作正常。但它有很多语言,所以我应该给每一种语言提供条件。
    • 希望这个新的编辑回答你的问题。以后请在提问时提前告诉您所有的要求/场景
    【解决方案2】:
    With string interpolation {{`${banner.home.heading_} some text ${banner.home.lang}`}}
    

    【讨论】:

    • 它不工作。
    • 我试过这样 {{${banner.home.heading_+banner.home.lang}}} 但没有工作
    • ${variable_or_function} text static ${other_variable_or_function} 引号之间的所有内容
    猜你喜欢
    • 1970-01-01
    • 2012-12-09
    • 2019-08-12
    • 1970-01-01
    • 2021-06-20
    • 2020-02-09
    • 2021-12-24
    • 2018-02-18
    • 1970-01-01
    相关资源
    最近更新 更多