I have a set of results in my Vue app. I want to be able to sort them alphabetically after I have searched. I then want them to return to the state before I clicked 'alphabetically' also. In my case its relevancy.
Relevancy is how it loads and before I choose 'Alphabetically'
The alphabetical option works fine but when I change it back to 'relevancy' it doesnt do anything and I dont understand why. To me it should just be 'return this.results();'
Can anyone help please?
<select
v-model="sortatoz"
@change="sortItems"
id="sortby"
aria-label="sortby"
>
<option disabled value="" selected>Select</option>
<option value="alphabetically">Alphabetically</option>
<option value="relevance">Relevance</option>
</select>
//sort drop down
sortItems() {
if (this.sortatoz === "alphabetically") {
return this.results.sort((a, b) =>
a.title > b.title ? 1 : -1
);
} else {
return this.results();
}
},
CodePudding user response:
So first of all, you copy your original set into a data variable you going to show inside your HTML.
So whenever you sort, you use this copied variable to sort. But whenever you want relevance again, you just copy the original again in the copied variable.
new Vue({
el: '#app',
data: {
list: ['A', 'C', 'B'],
copiedList: []
},
methods: {
sort() {
this.copiedList = [...this.list].sort((a, b) =>
a > b ? 1 : -1
);
},
unsort() {
this.copiedList = [...this.list]
}
}
})
<div id="app">
<button @click="sort">Sort</button>
<button @click="unsort">Unsort</button>
<div v-for="element in copiedList">
<div> {{ element }} </div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>