我想在 v-for 标记中设置一个自定义属性,如下代码所示,但是如何在 compulated
方法中获取此属性?
如何在此处获取自定义 Prop “data-index”?因为我想按索引为每个项目单独设置类。 我尝试过 $attrs.dataIndex、$dataset.index、$dataset.dataIndex,...,但没有人工作。
<li v-for="(item, index) in dataSource" :key="index" :class="classForItem">
// …
</li>
computed: {
classForItem() {
// How can I get the custom prop 'data-index' here? Because I want to set class for every item individually by index.
// I have tried $attrs.dataIndex, $dataset.index, $dataset.dataIndex, ..., but no one is worked.
}
}
最佳答案
您的问题不太清楚,但据我了解,您希望获得计算属性中循环的索引。对于计算属性来说这是不可能的。
如果您想获取索引,则必须将计算属性 ClassForItem 移动到“method”对象中,并将“index”作为参数发送,如下所示:
<li v-for="(item, index) in dataSource" :key="index" :class="classForItem(index)">
// …
</li>
methods: {
classForItem(index) {
console.log(index)
}
}
或者,如果您想访问数据集元素,可以使用以下方法:
<li v-for="(item, index) in dataSource" :key="index" :class="classForItem">
// …
</li>
methods: {
classForItem(event) {
console.log(event.target.dataset.index)
}
}
关于javascript - 我想在 v-for 标记中设置一个自定义属性,如下面的代码所示,但是如何在 `computed` 方法中获取此属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685349/