首页 > 解决方案 > 使用 v-for 遍历多个表行

问题描述

在 Vue 应用程序中,我想为集合中的每个项目呈现多个表行。目前呈现表格主体的(简化)标记是

<tbody>
<template v-for="item in collection">
    <tr>
        <td>{{item.foo}}</td>
        <td>{{item.bar}}</td>
    </tr>
    <tr>
        <td>{{item.foo2}}</td>
        <td>{{item.bar2}}</td>
    </tr>
</template>
<tbody>

但是,这个问题是没有定义键,如果我尝试添加一个

<template v-for="item in collection" :key="item.id">

然后我收到一个 eslint 错误,通知我只允许在真实元素上使用键。我无法<template>用真实元素替换,例如

<tbody>
<div v-for="item in collection" :key="item.id">
    <tr>
        <td>{{item.foo}}</td>
        <td>{{item.bar}}</td>
    </tr>
    <tr>
        <td>{{item.foo2}}</td>
        <td>{{item.bar2}}</td>
    </tr>
</div>
<tbody>

因为唯一可以嵌套在里面的元素<tbody><tr>. 如何在不违反 HTML 嵌套规则或 eslint 规则的情况下添加密钥?

标签: vue.js

解决方案


与其尝试重塑模板以适应数据,不如重塑数据以适应模板。这是一个将集合拆分为数组的示例,rows以便v-for可以将简单的元素与<td>元素一起使用:

<template>
  <tbody>
    <tr v-for="(item, index) in rows" :key="index">
      <td>{{ item.column1 }}</td>
      <td>{{ item.column2 }}</td>
    </tr>
  </tbody>
</template>
const ITEMS = [
  { foo: 'a1', bar: 'a2', foo2: 'b1', bar2: 'b2' },
  { foo: 'c1', bar: 'c1', foo2: 'd2', bar2: 'd2' },
];

export default {
  data() {
    return { items: ITEMS };
  },
  computed: {
    rows() {
      const result = [];
      this.items.forEach(({ foo, bar, foo2, bar2 }) => {
        result.push({ column1: foo, column2: bar });
        result.push({ column1: foo2, column2: bar2 });
      });
      return result;
    },
  },
};

推荐阅读