【问题标题】:Targeting last item in v-repeat with Vue JS使用 Vue JS 定位 v-repeat 中的最后一项
【发布时间】:2015-12-09 16:45:01
【问题描述】:

我有一个从 json 中提取的项目的 v-repeat 列表。

我想针对列表中的最后一项来更改其类别。

我该怎么做?我的代码在下面...

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

【问题讨论】:

  • 这个检索到的数据是html还是jsom?
  • @Alvaro 它是一个回显 json_encode($array) 的 php 脚本

标签: javascript vue.js


【解决方案1】:

对于 Vue 2.0,代码看起来略有不同:

<li v-for="(item, index) in items" v-bind:class="{last : index === (items.length-1)}">
  <i class="material-icons">{{ icon }}</i>
    {{ name }}
</li>

【讨论】:

    【解决方案2】:

    你只需要像这样添加v-class

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

    last 是您要添加的类

    【讨论】:

    • 如果我们在 v-repeat v-repeat="items | filter" 中应用一些过滤器,现在如何获取最后一个索引?
    • @AnandPatel 据我所知,您需要使用 this.$options.filters.filterBy() 方法在计算属性中对其进行过滤,然后它才能工作
    • 这不再适用于 vue 2.x。对于那些使用 2.x 的人,可以查看@Mariusz Jamro 的答案
    猜你喜欢
    • 2016-01-16
    • 2020-10-04
    • 2015-02-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2015-11-28
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多