I’m a newbie in Vue.js. I have the following lines of code in my HTML and JS file:
HTML
<div id="app"> <ul> <li v-for="item in items" v-bind:class="{{item.className}}">{{item.text}}</li> </ul> </div>
JS
var app = new Vue({ el: '#app', data: { items: [ { className: 'item-1', text: 'Item 1' }, { className: 'item-2', text: 'Item 2' }, { className: 'item-3', text: 'Item 3' } ] } })
What I want to happen is bind the value of each className
to the class attribute of each DOM element. I hope someone could correct me on this.
Advertisement
Answer
When using v-bind
you don’t need to use the {{...}}
syntax, because Vue already assumes you will want to use some kind of a property or object.
So you can for example output the value of each className
simply like this:
<li v-for="item in items" v-bind:class="item.className">{{item.text}}</li>
Or shorthand version:
<li v-for="item in items" :class="item.className">{{item.text}}</li>
Or if the classes are always going to follow the pattern of item-i
:
<li v-for="item, i in items" :class="`item-` + i">{{item.text}}</li>