You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何拼接API返回JSON响应的key并在Vue组件中渲染多语言内容

动态拼接JSON键名读取多语言内容的实现方案

问题原因

你当前的写法是直接对heading_字符串和lang字段值做字符串拼接,没有将拼接结果作为对象的属性名读取对应值,因此无法拿到预期的多语言内容。JavaScript 中读取对象的动态属性需要使用方括号访问语法。

实现方案

方案1:直接在模板中使用方括号语法

直接修改模板的插值表达式,用方括号传入动态拼接的属性名即可:

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

如果你的项目环境不支持模板内的模板字符串语法,也可以用普通字符串拼接写法:

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

方案2:使用计算属性封装(更推荐)

如果有多个多语言字段需要渲染,建议把逻辑抽到计算属性中,让模板更简洁易维护:

// Vue 2 写法示例
export default {
  computed: {
    // 也可以封装成通用方法,传入字段前缀直接返回对应内容
    currentBannerContent() {
      const { lang } = this.banner.home
      return {
        heading: this.banner.home[`heading_${lang}`],
        description: this.banner.home[`description_${lang}`]
      }
    }
  }
}

模板中直接调用计算属性即可,注意如果字段值是HTML片段,需要用v-html指令渲染,否则会转义HTML标签:

<template>
  <h1 class="banner-title">{{ currentBannerContent.heading }}</h1>
  <div class="banner-desc" v-html="currentBannerContent.description"></div>
</template>

内容的提问来源于stack exchange,提问作者matheen ulla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:24:03