5

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()
        }
    }
});
2
  • Is this retrieved data html or jsom? Commented Sep 13, 2015 at 16:56
  • @Alvaro its a php script that echo json_encode($array) Commented Sep 13, 2015 at 17:13

2 Answers 2

18

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>
Sign up to request clarification or add additional context in comments.

Comments

5

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

3 Comments

What if we apply some filter in v-repeat v-repeat="items | filter", how to get last index now?
@AnandPatel As far as I know, you need to filter it in computed properties using this.$options.filters.filterBy() method, then it would work
that does not work anymore for vue 2.x. For those who work with 2.x, can get a look at answer of @Mariusz Jamro

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.