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

Vue3中如何根据循环索引条件设置data属性?

解决方法

你当前的写法错误在于把:data-title绑定成了一个对象,Vue会将对象的键解析为属性名、值解析为是否渲染该属性的判断条件,这和你想要给data-title赋值为main的需求不符。

正确的写法是直接通过三元表达式判断索引,返回对应的值:

  • 当index === 0时,返回'main'作为data-title的属性值
  • 当索引不为0时,返回undefined或null,Vue会自动不渲染这个属性

修改后的代码如下:

<figure v-for="(project, index) in projects" :key="project.id">
  <figcaption>
    <span>
      {{ project.subtitle }}
    </span>
    <h2 :data-title="index === 0 ? 'main' : undefined">
      {{ project.title }}
    </h2>
  </figcaption>
</figure>

如果需要所有h2都保留data-title属性,只是非首项值为空,可以写成:

<h2 :data-title="index === 0 ? 'main' : ''">
  {{ project.title }}
</h2>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:44:54