Last active
October 15, 2017 00:56
-
-
Save fdcore/9639e03dd951c8376046e152b930f7ad to your computer and use it in GitHub Desktop.
vue sort list https://jsfiddle.net/kpLnk0L7/2/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="app"> | |
<div> | |
<button @click="sort_by='name'">name</button> | |
<button @click="sort_by='price'">price</button> | |
<button @click="sort_by='count'">count</button> | |
</div> | |
<hr> | |
<div> | |
<button @click="by_desc=true">ASC</button> | |
<button @click="by_desc=false">DESC</button> | |
</div> | |
<hr> | |
<ul> | |
<li v-for="i in sortBy(items, sort_by, by_desc)"> | |
<span v-text="i.name" :class="{b: sort_by== 'name'}"></span> / | |
<span v-text="i.price" :class="{b: sort_by== 'price'}"></span> / | |
<span v-text="i.count" :class="{b: sort_by== 'count'}"></span> | |
</li> | |
</ul> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.b { | |
font-weight: bold; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var app = new Vue({ | |
el: "#app", | |
data: { | |
sort_by: 'name', | |
by_desc: false, | |
items: [ | |
{ | |
name: "apple", | |
price: 1, | |
count: 10 | |
}, | |
{ | |
name: "orange", | |
price: 2, | |
count: 6 | |
}, | |
{ | |
name: "banana", | |
price: 3, | |
count: 1 | |
} | |
], | |
}, | |
methods: { | |
sortBy: function(items, key, desc) { | |
return items.sort(function(a, b) { | |
var x = a[key]; | |
var y = b[key]; | |
if(desc){ | |
return ((x < y) ? -1 : ((x > y) ? 0 : 1)); | |
} else{ | |
return ((x > y) ? -1 : ((x < y) ? 0 : 1)); | |
} | |
}); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment