Skip to content

Instantly share code, notes, and snippets.

@fdcore
Last active October 15, 2017 00:56
Show Gist options
  • Save fdcore/9639e03dd951c8376046e152b930f7ad to your computer and use it in GitHub Desktop.
Save fdcore/9639e03dd951c8376046e152b930f7ad to your computer and use it in GitHub Desktop.
<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>
.b {
font-weight: bold;
}
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