2017-10-28 73 views
0

遍历的项目清单这里是我的VUE例如:如何VueJS

new Vue({ 
    el: '#app', 
    data: { 
     showPerson: true, 
     persons: 
     [ 
      {id: 1, name: 'Alex'}, 
      {id: 2, name: 'Bob'}, 
      {id: 3, name: 'Chris'} 
     ], 
    }, 
    methods: { 
     nextPerson: function(){ 
     this.showPerson = false; 
     } 
    } 
    }); 

我试图走persons数组对象。我希望列表从数组的第一个元素开始,下面它应该是一个按钮,负责隐藏前一个元素并显示数组的下一个元素。一旦用户到达最后一个元素,Next按钮不应该回到第一个元素。

下面是HTML:

<div id="app"> 
    <ul v-for="person in persons"> 
    <li v-if="showPerson">{{person.name}}</li> 
    </ul> 
    <button @click="nextPerson">Next Person</button> 
</div> 

而且JSBin Link.此时此刻我只能显示和隐藏物品一下子,而不是一次一个。我怎样才能实现这个?

回答

1

这样做的方法之一是保留屏幕上显示的人的索引。我已将该变量命名为shownPersonIndex

然后,你需要点击按钮显示下一个人。因此,在click事件处理程序中,您需要将索引增加1.另外,您需要确保索引值不超过数组的长度。

nextPerson: function() { 
    if(this.shownPersonIndex < (this.persons.length - 1)) { 
    this.shownPersonIndex++; 
    } 
} 

最后,你可以使用一个计算,以显示当前显示的个人或内嵌式像this.persons[this.shownPersonIndex].name显示在屏幕上的人:所以我如下修改单击处理程序。

我使用v-if="this.shownPersonIndex != this.persons.length - 1"来隐藏“下一个”按钮,因为您到达阵列上的最后一个元素。

new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    shownPersonIndex: 0, 
 
    persons: [{ 
 
     id: 1, 
 
     name: 'Alex' 
 
     }, 
 
     { 
 
     id: 2, 
 
     name: 'Bob' 
 
     }, 
 
     { 
 
     id: 3, 
 
     name: 'Chris' 
 
     } 
 
    ], 
 
    }, 
 
    methods: { 
 
    nextPerson: function() { 
 
     if(this.shownPersonIndex < (this.persons.length - 1)) { 
 
     this.shownPersonIndex++; 
 
     } 
 
    } 
 
    }, 
 
    computed: { 
 
    shownPerson: function() { 
 
     return this.persons[this.shownPersonIndex]; 
 
    } 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script> 
 
<div id="app"> 
 
    Person: {{ shownPerson.name }} 
 
    <button v-if="this.shownPersonIndex != this.persons.length - 1" @click="nextPerson">Next Person</button> 
 
</div>

+0

我如何停止循环? 'if(this.shownPersonIndex == this.persons.length){this.shownPersonIndex = 0; }'是否将'showPersonIndex'重置为0? – Eisenheim

+1

是的,没错。我误解了你的问题。我认为你想完成第一个元素。我刚刚在答案中更新了这一点。 – Nisarg