javascript – 如何将class =“active”放入vuejs for循环中的第一个元素

前端之家收集整理的这篇文章主要介绍了javascript – 如何将class =“active”放入vuejs for循环中的第一个元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在努力学习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 }"
原文链接:https://www.f2er.com/js/159262.html

猜你在找的JavaScript相关文章