v-for 将单个对象视为对象集合

v-for treat single object the same as collection of objects

我有一个对象(我们称它为 employments),例如

{
 StartDate: "2018-01-01",
 Name: "Chris"
}

有时 employments 将是对象的集合,例如:

{
 StartDate: "2018-01-01",
 Name: "Chris"
},
{
 StartDate: "2017-01-01",
 Name: "Adam Brown"
}

如果我这样迭代

<div v-for="employment in employments">
    <p>{{employment.StartDate}}</p>
    <p>{{employment.Name}}</p>
</div>

第一个对象示例中给定的键(例如 employment.StartDate)将失败,因为 v-for 将遍历对象的键而不是整个对象。第二个对象集合将正常工作。

如何强制 v-for 对示例中给出的两个对象进行相同的处理?

您不能强制v-for将对象视为数组;在遍历数据之前,您需要将数据转换为正确的格式;类型检查可能是一个选项:

v-for="employment in (Array.isArray(employments) ? employments : [employments])"