text-aaa

VueJS - How do I associate multiple classes with an object created using v-for?

I wanted to do this:

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

Here is the code. https://jsfiddle.net/qwvwsgb9/

I can bind the value computed using v-for using the format without an object: class = "v.name"

HTML

<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 while I tried to apply it in an object format, an error occurs. How can i do this?

+4
source share
1 answer

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>
+6
source

Source: https://habr.com/ru/post/1679564/


All Articles