[英]How to show array in reverse in VUE?
I have simple array with items in which I push
new ones from time to time. 我有一个简单的数组,其中包含我会不时
push
新项目的项目。 New items comes via ajax
; 新项目通过
ajax
;
items.push({id: 1, title: 'a'});
items.push({id: 2, title: 'b'});
items.push({id: 3, title: 'c'});
items.push({id: 4, title: 'd'});
The main thing is that I need to show them in reverse like: 最主要的是,我需要反向显示它们,例如:
The problem is that I cant use unshift
as I need to have index
to items as I will need to do interactions with specific items. 问题是我无法使用
unshift
因为我需要对项目进行index
,因为我需要与特定项目进行交互。
So basically I'm searching for a way to push
items but show them like it was unshift
. 因此,基本上,我正在寻找一种方法来
push
项目,但要向他们展示它是unshift
。 Not actually reverse array. 实际上不是反向数组。
Just use a computed
property and you're done. 只需使用
computed
属性,就可以完成。 The reverse
method will reverse the items in an array in place, so I used the slice
method to create a new one. reverse
方法将在适当的位置反转数组中的项目,因此我使用slice
方法创建了一个新数组。
As for the unshift thing, the update order is already there when you use the push
method, so the order is just as simple as reverse the original array, you don't need to worry about it. 至于unshift,使用
push
方法时更新顺序已经存在,因此该顺序就像反转原始数组一样简单,您无需担心。
const app = new Vue({ el: '#app', data: { items: [] }, computed: { reversedArr() { return this.items.slice().reverse() } }, created() { this.items.push({id: 1, title: 'a'}) this.items.push({id: 2, title: 'b'}) this.items.push({id: 3, title: 'c'}) this.items.push({id: 4, title: 'd'}) } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script> <div id="app"> <div> <h3>Original</h3> <ul> <li v-for="item in items">{{item}}</li> </ul> </div> <div> <h3>Reversed</h3> <ul> <li v-for="item in reversedArr">{{item}}</li> </ul> </div> </div>
new Vue({ el: '#example', data: { items:[] }, mounted(){ this.items.push({id: 1, title: 'a'}) this.items.push({id: 2, title: 'b'}) this.items.push({id: 3, title: 'c'}) this.items.push({id: 4, title: 'd'}) } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script> <div id="example"> <div v-for="(item,index) in items.reverse()"> {{index+1}}. {{item.id}},{{item.title}} </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.