How to put class=“active” to first element in vuejs for loop

前端 未结 2 1994
猫巷女王i
猫巷女王i 2021-02-04 00:16

I\'m trying to learn vue.js. I\'m adding list of elements, I want to add class=\"active\" only to the first element in the for loop. following is my code:



        
相关标签:
2条回答
  • 2021-02-04 00:42

    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>

    Above is a snippet demonstrating a solution to your problem. Here's an outline of it:

    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

    The v-for directive has a second argument giving you the index of the item.

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

    Since you want the active class on the first item you can use an expression testing if the index is 0 and bind it to the class attribute.

    :class="{ 'active': index === 0 }"
    
    0 讨论(0)
  • 2021-02-04 00:43

    The easiest solution is to check every element if index is equal to 0 and then setting the active class (or the class you needed). Here is the code of class definition:

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

    Here is working example of making Bootstrap Tabs:

    <ul class="nav nav-tabs tab-nav-right" role="tablist">
        <li role="presentation" :class="{ 'active': index === 0 }" v-for="(value, index) in some_array" v-bind:key="index">
            {{some_array[index]}}
        </li>
    </ul>
    

    Also, if you have multiple classes you can mix them like this:

    :class="['tab-pane fade', (index === 0 ? 'active in' : 'something_else')]"
    
    0 讨论(0)
提交回复
热议问题