0👍
You don’t have to do it like this, use a computed
property instead, and you can see I used slice
, it’s because I want to copy the array instead of sorting the elements in place:
const app = new Vue({
el: '#app',
data: {
order: 'ASC',
list: [
{
name: 'item1',
date: 1 // possible here
},
{
name: 'item2',
date: 2 // possible here
},
{
name: 'item3',
date: 3 // possible here
},
{
name: 'test',
date: 4 // possible here
},
{
name: 'other',
date: 5 // possible here
}
]
},
computed: {
sortedList() {
return this.list.slice(0)
.sort((a, b) => {
if (this.order === 'ASC') {
return b.date - a.date;
}
return a.date - b.date;
})
}
},
methods: {
toggleSort(type){
this.order = type;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<div>
<button v-on:click="toggleSort('ASC')">ASC</button>
<button v-on:click="toggleSort('DSC')">DSC</button>
</div>
<div>
<div class="datemark" v-for="item in sortedList">
<div class="item">{{item.name}}</div>
</div>
</div>
</div>
And for your reference, if you’re actually doing comparison on real dates, use this instead”
array.sort(function(a,b){
// Turn your strings into dates, and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.date) - new Date(a.date);
});
- [Vuejs]-How to access variables handled by angularjs, using vuejs?
- [Vuejs]-@click vue calls form validate in laravel
Source:stackexchange.com