[Vuejs]-Sorting both directions in vuejs

2👍

you can use computed

var app = new Vue({
  el: '#app',
  computed: {
    sortedData () {
      if(!this.sort.field){
        return this.items
      }

      return this.items.concat().sort((a,b)=>{
        if(this.sort.desc){
          return a[this.sort.field] > b[this.sort.field] ? -1:1        
        }else{
          return a[this.sort.field] > b[this.sort.field] ? 1:-1                  
        }
      })
    }
  },
  data () {
    return {
      sort: {
        field: '',
        desc: true        
      },
      items: [
        { id: 1, name: 'Person 1', leave: 123.45 },
        { id: 2, name: 'John Smith', leave: 13.45 },
        { id: 3, name: 'Bill Smith', leave: 23.45 },
        { id: 4, name: 'John Doe', leave: 133.53 }
      ]
    }
  },
  methods: {
    doSort (field) {
      if(field == this.sort.field){
        this.sort.desc = !this.sort.desc
      }else{
        this.sort.field = field;
        this.sort.desc = true;
      }
    }
  }
})
  .user_row{
    display:flex;
  }
  .user_row>div{
    flex:1;
    text-align: center;
  }
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
   <a v-on:click="doSort('id')" href="javascript:">ID<span v-if="sort.field=='id'">({{sort.desc?'desc':'asc'}})</span></a>
   <a v-on:click="doSort('name')" href="javascript:">User<span v-if="sort.field=='name'">({{sort.desc?'desc':'asc'}})</span></a>
   <a v-on:click="doSort('leave')" href="javascript:">Leave Owing<span v-if="sort.field=='leave'">({{sort.desc?'desc':'asc'}})</span></a>

   <div id="page_list">
      <div class="user_row" v-for="item in sortedData">
         <div class="user_status">{{ item.id }}</div>
         <div class="username">{{ item.name }}</div>
         <div class="leave_owing">{{ item.leave }}</div>
       </div>
   </div>
</div>
👤jacky

Leave a comment