最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Targeting last item in v-repeat with Vue JS - Stack Overflow

programmeradmin1浏览0评论

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()
        }
    }
});

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()
        }
    }
});
Share Improve this question asked Sep 13, 2015 at 16:37 nolandnoland 1252 silver badges10 bronze badges 2
  • Is this retrieved data html or jsom? – Alvaro Silvino Commented Sep 13, 2015 at 16:56
  • @Alvaro its a php script that echo json_encode($array) – noland Commented Sep 13, 2015 at 17:13
Add a comment  | 

2 Answers 2

Reset to default 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>

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

发布评论

评论列表(0)

  1. 暂无评论