Reputation: 4596
I have simple array with items in which I push
new ones from time to time. New items comes via 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.
So basically I'm searching for a way to push
items but show them like it was unshift
. Not actually reverse array.
Upvotes: 1
Views: 3794
Reputation: 786
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>
Upvotes: 1
Reputation: 4438
Just use a computed
property and you're done. The reverse
method will reverse the items in an array in place, so I used the slice
method to create a new one.
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.
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>
Upvotes: 5