1

I'm making a sorting function by Vue js

I'd like to make a list by the ID order for the default, then, sorting function can be occured by clicking asc/desc by name button.

Also, when clicking all button, the list sorts by the ID order again and adding the class named is-active

I know I've added sorting function by the default but I don't know how to combine with the order of ID number.

If somebody know how to, please help.

Thank you

new Vue({
  el: '#app',
  data: {
    allItem: true,
    order: null,
    list: [],
  },
  created: function () {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(function (response) {
      this.list = response.data
    }.bind(this)).catch(function (e) {
      console.error(e)
    })
  },
  methods: {
    all: function() {
      this.full = true                 //for button class 'is-active'... NOT WORKING ...
    },
  },
  computed: {
    sort: function() {
      console.log(this.order);
      return _.orderBy(this.list, 'name', this.order ? 'desc' : 'asc')   //loadash
    },
    sorted: function() {
      if (this.order || !this.order) { //sort by arc/desc
        this.ordered = true            //for button class 'is-active'... NOT WORKING ...
        this.allItem = false           //for button class 'is-active'... NOT WORKING ...
        console.log(this.order);
        return this.sort

      } else if (this.order = null){   //defalut order by ID number ... NOT WORKING ...
        this.ordered = false           //for button class 'is-active'... NOT WORKING ...
        console.log(this.full);
        return this.list
      }

    },
  }
})
span {font-weight: bold;}
.is-active {background: turquoise;}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<div id="app">
  <ul>
    <li v-for="item in sorted" :key="item.id">
      <span>ID:</span> {{item.id}} ,  <span>Name:</span> {{item.name}} ,  <span>Company:</span> {{item.company.name}}
    </li>
  </ul>

  <button :class="{'is-active': allItem}"  @click="all">all</button>
  <button :class="{'is-active': ordered}"  @click="order=!order">asc/desc by name</button>
</div>

2 Answers 2

1

new Vue({
  el: '#app',
  template: `
    <div v-if="!loading">
      <ul>
        <li v-for="item in sorted" :key="item.id">
          <strong>ID:</strong> {{item.id}} ,  
          <strong>Name:</strong> {{item.name}} ,      
          <strong>Company:</strong> {{item.company.name}}
        </li>
      </ul>

      <button :class="{ 'is-active': sortId === 'id' }"  @click="sortById">all</button>
      <button :class="{ 'is-active': sortId === 'name' }"  @click="sortByName">asc/desc by name</button>
    </div>
  `,
  data() {
    return {
      list: [],
      loading: true,
      sortId: "id",
      directionAsc: true,
    };
  },
  computed: {
    sorted() {
      const DIRECTION = this.directionAsc ? "asc" : "desc";
      return _.orderBy(this.list, [this.sortId], [DIRECTION]);
    },
  },
  created: function() {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(function(response) {
        this.list = response.data;
        this.loading = false;
      }.bind(this)).catch(function(e) {
        console.error(e)
      })
  },
  methods: {
    sortById() {
      if (this.sortId === "id") {
        return;
      }
      this.sortId = "id";
      this.directionAsc = true;
    },

    sortByName() {
      if (this.sortId === "name") {
        this.directionAsc = !this.directionAsc;
      } else {
        this.sortId = "name";
      }
    },
  },
})
.is-active {
  background: turquoise;
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<div id="app"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. It took me some time to understand your code. But I learned a lot from it, espacially to devide _.orderBy stuff. Can I ask one question if you don't mind? Why did you add this.loading = false; for axios. Is it for asynchronous? like to wait for connecting to the API?
Yes, I would put a spinner here. <spinner v-if="loading"></spinner><div v-else></div>
1

You can do it simpler with computed and switch. Code:

new Vue({
  el: '#app',
  data: {
    sort: '',
    order: false,
    list: [],
  },
  created: function () {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(function (response) {
      this.list = response.data
    }.bind(this)).catch(function (e) {
      console.error(e)
    })
  },
  methods: {
    setSort(sort) {
        if(this.sort === sort) {
            this.toggleOrder();
        } else {
            this.sort = sort;
        }
    }
    toggleOrder() {
        this.order = !this.order;
    }
  },
  computed: {
    sortedList: function() {
        switch(this.sort) {
            case 'name':
                return _.orderBy(this.list, 'name', this.order ? 'desc' : 'asc');
            case 'id':
                return _.orderBy(this.list, 'id', this.order ? 'desc' : 'asc');
            default:
                return this.list;
        }
    },
  }
})

And template:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<div id="app">
  <ul>
    <li v-for="item in sorted" :key="item.id">
      <span>ID:</span> {{item.id}} ,  <span>Name:</span> {{item.name}} ,  <span>Company:</span> {{item.company.name}}
    </li>
  </ul>

  <button :class="{'is-active': !sort}"  @click="setSort('')">all</button>
  <button :class="{'is-active': sort === 'name'}"  @click="setSort('name')">asc/desc by name</button>
</div>

2 Comments

Thank you very much for your answer. I'm gonna practice your way. I give solved state to the other guy who gave me the answer earlier. Sorry about it.
Thanks a lot. I appreciate that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.