如何在Vue3中有条件地设置数据属性?

huangapple go评论83阅读模式
英文:

How to conditionally set a data-attribute in vue3?

问题

I'm trying, depending on if my loops index is 0 or not to set a data-attribute on a h2-tag. What i want is that it should render as data-title="main" if the index is 0. How would i do that? Now its not rendering the data-attribute at all.

Code:

(projects is an already parsed json, without, errors)

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

I'm trying, depending on if my loops index is 0 or not to set a data-attribute on a h2-tag. What i want is that it should render as data-title="main" if the index is 0. How would i do that? Now its not rendering the data-attribute at all.

Code:

(projects is an already parsed json, without, errors)

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

答案1

得分: 0

Here are the translated parts:

不同于需要一个对象的style属性

<div :style="{ display: index == 0 ? "block" : undefined }" />

大多数其他属性具有不同的值类型
在你的情况下,它是string

<div :data-title="index == 0 ? 'main' : 'otherwise'" />

传递undefinednull以使Vue完全删除属性。

<div :data-title="index == 0 ? 'main' : undefined " />
英文:

Unlike style attribute that wants a object

<div :style="{ display: index == 0 ? "block" : undefined }" />

most of the other attributes have other value types
In your case, it's string

<div :data-title="index == 0 ? 'main' : 'otherwise'" />

Pass undefined or null to make Vue remove the attribute completely.

<div :data-title="index == 0 ? 'main' : undefined " />

huangapple
  • 本文由 发表于 2023年5月15日 05:24:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76249748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定