【问题标题】:Print data in table using for loop in VueJS在 VueJS 中使用 for 循环打印表格中的数据
【发布时间】:2020-12-25 03:34:30
【问题描述】:

成功获取API数据后,结果如下:

{
  fred: {
    foo: bar,
    baz: qux,
    fred: xzzy
  },
  thud: {
    foo: bar,
    baz: qux,
    fred: xzzy
  },
  plugh: {
    foo: bar,
    baz: qux,
    fred: xzzy
  }
}

我需要将表格中的数据显示如下:

th th 
fred bar xzzy
thud bar xzzy
plugh bar xzzy

使用下面的代码,我只完成了<tr>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<tr v-for="(values, key) in object" v-bind:key="key.id">
  <th scope="row">{{ key }}</th>
  <td v-for="(values, key) in object" v-bind:key="values.id">{{ values.last }}</td>
</tr>

打印如下:

th th 
fred bar bar bar
thud qux qux qux
plugh xzzy xzzy xzzy

如果参考一个好的嵌套数组/对象教程也将不胜感激。

【问题讨论】:

    标签: vue.js vuejs2 v-for


    【解决方案1】:

    也许这对你有用:

    new Vue({
      el: '#app',
      data: {
        exampleObject: {
          "fred": {
            "foo": "bar",
            "baz": "qux",
            "fred": "xzzy"
          },
          "thud": {
            "foo": "bar",
            "baz": "qux",
            "fred": "xzzy"
          },
          "plugh": {
            "foo": "bar",
            "baz": "qux",
            "fred": "xzzy"
          }
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
    <div id="app">
      <table>
        <tr v-for="(values, key) in exampleObject" v-bind:key="key">
          <th scope="row">{{ key }}</th>
          <td v-for="(val, keyCol) in values" v-if="keyCol != 'baz'" v-bind:key="keyCol">{{ val }}</td>
        </tr>
      </table>
    </div>

    同样的例子,但在 codepen 上: https://codepen.io/fabiogarcia/pen/poyprYw

    【讨论】:

    • 错误 'v-for' 指令中的 'values' 变量应替换为返回过滤数组的计算属性。你不应该混合 'v-for' 和 'v-if' vue/no-use-v-if-with-v-for
    【解决方案2】:

    试试吧:

    <tr v-for="(valuesParent, key) in object" v-bind:key="valuesParent">
      <th scope="row">{{ key }}</th>
      <td v-for="(values, key) in valuesParent" v-bind:key="values">{{ values }}</td>
    </tr>
    

    【讨论】:

      猜你喜欢
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 2013-02-20
      相关资源
      最近更新 更多