Search code examples
classvue.jsbind

VueJS - How can I bind multiple class from object that created by v-for?


I wanted to make it like this:

    <ul>
      <li class="aaa active">text-aaa</li>
      <li class="bbb">text-bbb</li>
      <li class="ccc">text-ccc</li>
    </ul>

Here's the code. https://jsfiddle.net/qwvwsgb9/

I can bind value calculated by v-for by using non-object format :class="v.name"


    <div id="app">
      <ul>
        <li v-for="v, i in listAry" :class="{v.name:true,active:active==i}">{{ v.text }}</li>
      </ul>
    </div>
   
script:

    let vm = new Vue({
      el: "#app",
      data: {
        active:0,
        listAry: [{
          name: 'aaa',
          text: 'text-aaa'
        }, {
          name: 'bbb',
          text: 'text-bbb'
        }, {
          name: 'ccc',
          text: 'text-ccc'
        }]
      }
    })

but as long as I tried to apply it in object format, the error occurs. How can I do it?


Solution

  • Try something like this :class="[{ active: active === i }, v.name]"

    <div id="app">
      <ul>
        <li v-for="v, i in listAry" :class="[{ active: active === i }, v.name]">
          {{ v.text }}
        </li>
      </ul>
    </div>