user13928344
user13928344

Reputation: 216

Vue JS sort and then return to previous state

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
                class="form-control col-4 col-lg-5"
                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();
       
      }
    },

Upvotes: 0

Views: 157

Answers (1)

Wimanicesir
Wimanicesir

Reputation: 5122

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: []
  },
 mounted () {
  this.unsort()
 },
 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>

Upvotes: 1

Related Questions