我正在努力学习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" } ] } } }
帮帮我.
解决方法
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://vuejs.org/v2/guide/list.html#Basic-Usage
v-for指令有第二个参数,为您提供项目的索引.
v-for="(item,index) in items"
由于您希望第一项上的活动类,因此如果索引为0,则可以使用表达式测试并将其绑定到class属性.
:class="{ 'active': index === 0 }"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。