Skip to content

Instantly share code, notes, and snippets.

@Shenglian
Created May 24, 2017 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shenglian/8d79ecfb6e43f0b6247f3ae7e4b76625 to your computer and use it in GitHub Desktop.
Save Shenglian/8d79ecfb6e43f0b6247f3ae7e4b76625 to your computer and use it in GitHub Desktop.
vuejs 2.x filter
new Vue({
el: '#app',
data() {
return {
testData: [{ name: 'foo' }, { name: 'bar' }, { name: 'foobar' }, { name: 'test' }],
filterValue: '',
sortAsc: true
};
},
computed: {
filteredAndSortedData() {
let result = this.testData;
if (this.filterValue) {
result = result.filter(item => item.name.includes(this.filterValue));
}
let ascDesc = this.sortAsc ? 1 : -1;
return result.sort((a, b) => ascDesc * a.name.localeCompare(b.name));
}
},
methods: {
invertSort() {
this.sortAsc = !this.sortAsc;
}
}
});
<div id="app">
<div>{{filteredAndSortedData}}</div>
<div>
<input type="text" v-model="filterValue" placeholder="Filter">
<button @click="invertSort()">Sort asc/desc</button>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment