首页 > 解决方案 > 使用 v-for 在数组中显示数组的正确方法

问题描述

我正在尝试显示文本数组/对象的值,但我得到一个输出,试图向我显示数组/对象中每个名称的段落。

链接到当前结果:当前结果

我对 vue.js 还很陌生,所以欢迎任何提示!

<template>
  <div class="education center">
    <div v-if="object.timelines != null">
      <template v-for="(time,index) in object.timelines">
        <p :key="index">{{ time.schoolyear }}</p>
        <div :key="index" v-bind="time" v-for="(text,index) in time.text">
          <p :key="text">Degree: {{ text.degree }}</p>
          <p>Institution: {{ text.institution }}</p>
          <p>Where: {{text.where}}</p>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
export default {
  el: ".education",
  data: function() {
    return {
      object: {
        timelines: [
          {
            schoolyear: "2016 - 2017",
            text: [
              { degree: "Applied Computer Science" },
              { institution: "Thomas More University of Applied Science" },
              { where: "Belgium, Geel" }
            ]
          },
          {
            schoolyear: "2018 - 2019",
            text: [
              { degree: "Business IT" },
              { institution: "HAMK University of Applied Science" },
              { where: "Finland, Hämeenlinna" }
            ]
          }
        ]
      }
    };
  }
};
</script>

我只想为 schoolyear="2016 - 2017" 显示一次 text.degree

标签: arraysvue.jsv-for

解决方案


我并不完全清楚你想要什么,但也许是你想要遍历.text数组,并且对于数组中的每个条目,显示它的键和它的内容。如果是这样,您可以尝试以下方法:

<p v-for="(entry, index) in time.text" :key="index">
    {{Object.keys(entry)[0]}}: {{Object.values(entry)[0]}}
</p>

如果您需要担心键的标题大小写,您可以使用计算属性来转换数组,或者定义一个方法来转换每个字符串。


推荐阅读