Skip to content
Advertisement

Vuejs: how do you pass class(classes) to template?

What is the right syntax to pass class to %item.class% in the following code? Any syntax like [item.class] or {{ item.class }} passes it as string without render. How to pass it properly?

How to pass several classes and apply to several tags (a, span etc.) nested in one template? Pass an array? How to iterate it?

<component v-for="item in List" 
                :item="item"
                :class="item.class"
</component>


let component = Vue.component('component', {
       props: ['item'],
       template: `<li class=" %item.class% ">
                     <a class="fa %item.class% "></a>
                     <span class="fa %item.class%"></span>
                  </li>`
       }),
       data: function (){
        return {
            List: [
                {key:0, class:'someClass'},

            ]
        }
    },
 })

Thanks beforehands 🙂

Advertisement

Answer

Solution: You can pass an object to v-bind:class :class to dynamically toggle classes:

<li :class="item.class">
                     <a class="fa" :class="item.class"></a>
                     <span class="fa" :class="item.class"></span>
                  </li>

Binding HTML Classes

  • Object Syntax :
<div v-bind:class="{ active: isActive }"></div>
data: {
  isActive: true
}
  • Array Syntax:
<div v-bind:class="[activeClass, errorClass]"></div>
data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}

More Info Official documentation

Advertisement