英文:
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'" />
传递undefined
或null
以使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 " />
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论