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

VueJS2与Lodash4:如何在HTML表格中嵌套v-for展示字段新旧值

问题根因

你在<td>标签内嵌套v-for遍历全部旧值对象,会导致每一行新字段数据都渲染出和旧值字段总数相等的<td>元素,既会打乱表格结构,也无法实现新字段和对应旧值的匹配。

解决方案

有两种实现方式可选:

方案1:直接修改模板(改动最小)

不需要循环旧值对象,直接用当前行的字段名拼接_old后缀,从旧值对象中取值即可,修改后的表格代码如下:

<table class="table">
  <thead>
    <tr>
      <th scope="col">Field</th>
      <th scope="col">Old</th>
      <th scope="col">New</th>
    </tr>
  </thead>
  <tbody>
    <tr
      v-for="(value, field, index) in filteredFieldsWithNewValues"
      :key="index"
    >
      <th scope="row">{{ field }}</th>
      <!-- 去掉嵌套v-for,直接取对应旧值 -->
      <td>{{ filteredFieldsWithOldValues[`${field}_old`] }}</td>
      <td>{{ value }}</td>
    </tr>
  </tbody>
</table>

方案2:优化计算属性(逻辑更清晰)

新增一个计算属性直接返回配对好的新旧值数组,避免在模板中做字符串拼接逻辑,代码更易维护:

  1. 新增计算属性:
fieldPairs() {
  const result = []
  Object.entries(this.filteredFieldsWithNewValues).forEach(([field, newValue]) => {
    result.push({
      field,
      newValue,
      // 匹配对应旧值,不存在时返回空字符串兜底
      oldValue: this.country[`${field}_old`] ?? ''
    })
  })
  return result
}
  1. 修改模板直接遍历配对后的数组:
<table class="table">
  <thead>
    <tr>
      <th scope="col">Field</th>
      <th scope="col">Old</th>
      <th scope="col">New</th>
    </tr>
  </thead>
  <tbody>
    <tr
      v-for="(item, index) in fieldPairs"
      :key="index"
    >
      <th scope="row">{{ item.field }}</th>
      <td>{{ item.oldValue }}</td>
      <td>{{ item.newValue }}</td>
    </tr>
  </tbody>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:00:02