vue.js - 使用 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 规则的情况下添加密钥?
解决方案
与其尝试重塑模板以适应数据,不如重塑数据以适应模板。这是一个将集合拆分为数组的示例,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;
},
},
};
推荐阅读
- git - Git推送上游分支跟踪
- django - 手动将文件传递给 Django 表单
- android - FAILURE: Build failed with an exception. (flutter)
- java - Java Audioclip: new AudioClip(s) with remote URL creates UI lags
- c# - Unable to connect to MongoDB container from .NET Core WebAPI container, but can connect normally
- reactjs - 一个域中的多个 Web
- pointers - 使用 func golang 传递指针的值
- reactjs - React Hook useEffect has a missing dependency: 'fetchComments'. Either include it or remove the dependency array
- javascript - If label doesn't fit in the div of treemap Highcharts it should wrap to second line
- python - pip 找不到所需的版本