gpt4 book ai didi

javascript - 如何将类 ="active"放入 vuejs for 循环中的第一个元素

转载 作者:可可西里 更新时间:2023-11-01 01:36:49 24 4
gpt4 key购买 nike

我正在尝试学习 vue.js。我正在添加元素列表,我只想将 class="active" 添加到 for 循环中的第一个元素。以下是我的代码:

<div class="carousel-inner text-center " role="listbox">
<div class="item" v-for="sliderContent in sliderContents">
<h1>{{ sliderContent.title }}</h1>
<p v-html="sliderContent.paragraph"></p>
</div>
</div>

所以第一个元素应该是这样的:

<div class="item active">
<h1>WELCOME TO CANVAS</h1>
<p>Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas</p>
</div>

我能够获取数据,因此一切正常。

下面是我的脚本代码:

<script>
export default{
data() {
return {
sliderContents: [
{
title: "WELCOME TO CANVAS",
paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas"
},
{
title: "WELCOME TO CANVAS",
paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas"
},
{
title: "WELCOME TO CANVAS",
paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas"
},
{
title: "WELCOME TO CANVAS",
paragraph: "Create just what you need for your Perfect Website. Choose from a wide<br>range of Elements & simple put them on your own Canvas"
}
]
}
}
}

帮帮我。

最佳答案

const TextComponent = {
template: `
<p>{{ text }}</p>
`,

props: ['text'],
};

new Vue({
components: {
TextComponent,
},

template: `
<div>
<text-component
v-for="(item, index) in items"
:class="{ 'active': index === 0 }"
:text="item.text">
</text-component>
</div>
`,

data: {
items: [
{ text: 'Foo' },
{ text: 'Bar' },
{ text: 'Baz' },
],
},
}).$mount('#app');
.active {
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

上面是一个片段,展示了您的问题的解决方案。这是它的概要:

Inside v-for blocks we have full access to parent scope properties. v-for also supports an optional second argument for the index of the current item.

https://v2.vuejs.org/v2/guide/list.html#Basic-Usage

v-for 指令有第二个参数给你项目的索引。

v-for="(item, index) in items"

因为您想要在第一个项目上使用 active 类,您可以使用表达式测试 index 是否为 0 并将其绑定(bind)到类属性。

:class="{ 'active': index === 0 }"

关于javascript - 如何将类 ="active"放入 vuejs for 循环中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42487711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com