What is the best way to create a list and incorporate a sorting function using Vue JS?

Currently working on creating a sort function with Vue js

The goal is to initially display a list in ID order by default, and then allow sorting by clicking the asc/desc by name button.

Additionally, when the all button is clicked, the list should revert back to being sorted by ID order and add the class is-active.

I have successfully implemented the default sorting function, but I am struggling with integrating it with the ID number order.

If anyone has experience with this and can offer some guidance, it would be greatly appreciated.

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e9889180869aa9d9c7d8dec7d8">[email protected]</a>/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7cbc8c3c6d4cfe793899690899692">[email protected]</a>/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>

Answer №1

Initializing Vue Component with axios API call to fetch user data and display in a sorted order based on ID or 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>

Answer №2

If you want to simplify things, you can utilize computed properties and a switch statement. Check out the code below:

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;
        }
    },
  }
})

Here is the corresponding template:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c5152574740087854263b3d26337a38345837323a33387538233a">[email protected]</a>/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7427222d29682c36293328333507952025212ac3252f29252">[email protected]</a>/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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating HTML elements using JavaScript

Below is the code snippet in question: function getAllRecipes(){ $.ajax({ type: "GET", url: "https://api.npoint.io/7493fda05b8038212eed", beforeSend: function() { $("#AllRecipe").html('Fetching...') }, success: func ...

Tips for filtering array elements in MongoDB based on element dataIf you want to eliminate certain elements from an array in MongoDB based

Seeking guidance on writing a Mongo query to remove elements from an array based on specific data. { "_id": ObjectId("ajdi293akjf83rhfsf398"), "one": "oneData", "two": [ { "_id":ObjectId("akjf82ijikfj83jkfkj3"), "valu ...

The server encountered a 500 Internal Server Error because it could not read the 'username' property of an undefined object

When attempting to register a user in a mongodb database using express, a POST call was made to localhost:3000/users/register The request body included: { "firstName": "Jason", "lastName": "Watmore", "username": "jason", "email": "<a ...

Translating a few lines of JavaScript into C#

I'm looking to convert some code from JavaScript to C#, but I'm having trouble grasping a certain section... function getHisto(pixels) { var histosize = 1 << (3 * sigbits), histo = new Array(histosize), inde ...

Creating a visual selection menu with icon options using jQuery or a similar framework

Currently, I am working on designing an HTML form that includes a field where users must select from a set of options such as sunny, cloudy, rainy, and more. I am seeking a creative alternative to using the <select> or <radio> input elements. ...

Ways to safeguard your API endpoint

Just starting out with Node.js/Express, I'm looking to have my front end retrieve data from an endpoint ('/1') without displaying the JSON data to users when they access that specific endpoint. Any guidance on how to accomplish this would be ...

The function getStaticPaths() will generate a 404 error, indicating that the page

I have encountered a persistent issue with the getStaticPaths() function throwing a 404 error. After investigating, I suspect that the problem may lie in the implementation of the getAllPostIds() function, which is supposed to generate an array of object ...

Dynamically parsing JSON data with jQuery

I have some JSON data that looks like this: { "default": [ [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ] ], "direct": [ [ ...

JavaScript lacks the power to persuade the mouse into altering its cursor

I am encountering an issue with my ASP.NET page that contains an Infragistics webgrid. I have implemented Javascript methods to handle the mouseover and mouseout events on the grid rows, changing the mouse cursor to a pointer and back to the default as use ...

What is the best way to combine several packed props simultaneously?

After attempting the following, I encountered the following error: Unhandled Runtime Error TypeError: navbar.makeButtonClick is not a function Source .next/static/chunks/pages/index.js (19:29) @ onClick 17 | return( 18 | <button href='#&apo ...

Is it necessary to have bidirectional relationships in Sequelize?

In my database, I have two existing tables: "user" which contains columns "id" and "depId", and "department" with columns "id" and "name". The column user.depId is a foreign key referencing department.id. Now, I want to create a sequelize model for this r ...

What is preventing the installation of bootstrap-vue on my system?

I'm facing an issue while attempting to set up bootstrap-vue in my vue project. I used the command npm install bootstrap-vue bootstrap, but encountered a perplexing error message. npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class=" ...

What is causing my PHP array to fail to display as an array in JavaScript?

As a beginner in JavaScript coding, I am currently trying to query my MySQL database to retrieve disabled days for the date picker. Although I have made progress, I am facing an issue where only one set of values is being stored in the JavaScript variable ...

The ChartistJs is unable to find the property '_index' of an undefined value, either being 0 or null

I recently incorporated chartistJS to display charts on my website. I have successfully implemented the 'onClick' function provided by chartist. Here is a snippet of the code I used: public horizontalBarchartoptions = { 'onClick&apo ...

Is there a way to sort data by year and month in mongodb?

I'm trying to filter data by year in MongoDB based on a specific year and month. For example, if I pass in the year 2022, I only want to see data from that year. However, when I try using the $gte and $lte tags, it returns empty results. Can someone g ...

The Express/Mongoose route consistently modifies the identical item

I'm encountering an issue where any attempt to update or create a new item results in only creating one item and then updating that same item regardless of the input. Is there something incorrect with this route? // @route POST api/item // @desc ...

Exploring History Navigation with AngularJS: Leveraging $routeParams and $location

I have been diligently working on developing a question bank and have successfully coded most of the elements. However, I would like to enhance the user experience by implementing browser history for easy navigation through the questions. If you want to c ...

The Raycaster.intersectObjects function in Three.js is only able to detect intersections with the front surface

My current project involves generating a world filled with blocks on the ground upon mouse click (using mouse click coordinates that I've calculated). To ensure that each new block doesn't intersect with existing ones, I implemented a check using ...

Security at risk - watermark.js

I have been utilizing watermark.js to protect images on my WordPress website. During testing, I encountered an error in img.src = gcanvas.toDataURL();. Despite my efforts, I have not been able to locate where this value should be set. Here is the code th ...

The difference between using `for(var i in aArray)` and `for(i=0; i<aArray.length; i++)` lies

Can someone help me understand if the functions in_array_orig and in_array_new are essentially the same? I'm also confused about the results when comparing arrays aArr1 and aArr2. Could someone explain this to me? Thank you. Below is a snippet of my ...