我正在尝试创建一个 v-for 来显示包含多组练习的列表。我在每个练习下面为每组创建了一个循环,其中包含一行。
我的数据如下所示。
const exercises = [
{ id: 1, name: exercise1, sets: 3 },
{ id:2, name: exercise2, sets: 2 }
{ id:3, name: exercise3, sets: 4 }
]
我的组件看起来像这样:
<template v-for="exercise in exercises" :key="exercise.id">
<span> {{ exercise.name }} </span>
<template v-for="set in exercise.sets" :key="set">
<span @click="completeSet()"> {{ set }} </span>
</template>
</template>
现在,我希望能够通过单击事件将每组上的值设置为 true 或 false,将每组标记为已完成。但我不确定如何执行此操作,因为每个集合都没有用于设置值的属性,因为它循环遍历一个数字。
解决这个问题的正确方法是什么?
最佳答案
首先,您不能循环遍历数字。为了能够循环这些集合,您必须
<template v-for="let set = 0; set < exercise.sets; set++" :key="set">
<span @click="completeSet()"> {{ set }} </span>
</template>
但是,为数字设置属性同样是不可能的。您必须准备好数据才能进行调整:
const exercises = [
{ id: 1, name: 'exercise1', sets: 3 },
{ id: 2, name: 'exercise2', sets: 2 } ,
{ id: 3, name: 'exercise3', sets: 4 }
].map(exercise => ({
id: exercise.id,
name: exercise.name,
sets: Array.from(
{ length: exercise.sets },
() => ({ completed: false })
),
}))
关于javascript - 将 for 循环中每个项目的值设置为 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73525303/