Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Targeting last item in v-repeat with Vue JS

I have a v-repeat list of items that are pulled from json.

I want to target the last item in the list to change its class.

How would I do this? My code is below...

HTML

<div id="app">
...
            <ul id="menu">
                <li v-repeat="items">
                    <i class="material-icons">{{ icon }}</i>
                    {{ name }}
                </li>
            </ul>
</div>

JS

var apiUrl = 'inc/menu.json.php'

new Vue({
    el: '#app',
    data: {
        active: true,
        items: []
    },
    ready: function(){
        this.fetchData()
    },
    methods: {
        toggle: function () {
            this.active = !this.active;
        },
        fetchData: function(){
            var xhr = new XMLHttpRequest(),
                self = this
            xhr.open('GET', apiUrl)
            xhr.onload = function () {
                self.items = JSON.parse(xhr.responseText)
            }
            xhr.send()
        }
    }
});
like image 654
noland Avatar asked Sep 13 '15 16:09

noland


2 Answers

For Vue 2.0 the code looks slighly different:

<li v-for="(item, index) in items" v-bind:class="{last : index === (items.length-1)}">
  <i class="material-icons">{{ icon }}</i>
    {{ name }}
</li>
like image 74
Mariusz Jamro Avatar answered Oct 15 '22 16:10

Mariusz Jamro


You just need to add v-class like this

<li v-repeat="items" v-class="last : $index === (items.length-1)">
  <i class="material-icons">{{ icon }}</i>
    {{ name }}
</li>

where last is the class you want to add

like image 32
Jihad Waspada Avatar answered Oct 15 '22 16:10

Jihad Waspada