Implementing sorting functionality in a list with Vue.js by incorporating an arrow icon in the column using v-bind

Is there a way to implement sorting functionality in Vue.js by clicking on table headers and displaying an arrow to indicate the sorting order? I am struggling with creating a function in Vue for sorting and using v-bind to add the arrow. Can someone guide me on how to approach this using Vue, CSS, and HTML?

     <div id="app">
      <table>
        <thead>
          <tr></tr>
            <th v-for="(header, key) in column" :key="key" v-on:click="sortTable(key)">{{ header }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in rows" :key="row.id">
            <td>{{ row.id }}</td>
            <td>{{ row.name }}</td>
            <td>{{ row.phone }}</td>
          </tr>
        </tbody>
      </table>
    </div>

and my js

var app = new Vue({
  el: "#app",
  data: {
    column: {
      id: "ID",
      name: "Full Name",
      phone: "Phone",
    },
    rows: [],
    sortColumn: null,
    sortOrder: "asc",
  },
  computed: {
    sortedRows() {
      if (!this.sortColumn) {
        return this.rows;
      }
      return this.rows.slice().sort((a, b) => {
        const aValue = a[this.sortColumn];
        const bValue = b[this.sortColumn];
        if (typeof aValue === "string") {
          return (
            aValue.localeCompare(bValue) * (this.sortOrder === "asc" ? 1 : -1)
          );
        }
        return (aValue - bValue) * (this.sortOrder === "asc" ? 1 : -1);
      });
    },
  },
  methods: {
    async fetchData() {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );
      const finalRes = await response.json();
      this.rows = finalRes;
    },
    sortTable(key) {
      if (key == this.sortColumn) {
        this.sortOrder = this.sortOrder === "asc" ? "desc" : "asc";
      } else {
        this.sortColumn = key;
      }
      alert(this.sortColumn);
    },
  },
  mounted() {
    this.fetchData();
    this.sortTable(key);
  },
});

CSS:

table {
  text-align: left;
  font-family: "Open Sans", sans-serif;
  width: 500px;
  border-collapse: collapse;
  border: 2px solid #444777;
  margin: 10px;
}

table th {
  background: #444777;
  color: #fff;
  padding: 5px;
  min-width: 30px;
}

table td {
  padding: 5px;
  border-right: 2px solid #444777;
}

table tbody tr:nth-child(2n) {
  background: #d4d8f9;
}

My expected outcome: https://i.sstatic.net/31Sci.jpg

Answer №1

To effectively tackle your issue, consider breaking it down into two separate problems.

Application of Classes

You can assign a class using a different syntax as shown below:

<div :class="{'nameOfClass': condition}"></div>

In your scenario, it would look something like this:

<div :class="{sortDirection: sortBy === header}"></div>

https://v2.vuejs.org/v2/guide/class-and-style.html

Data Sorting

You've taken the right initial steps. However, your method does not actually perform any sorting. Sorting requires three conditions: greater than, less than, and equal to.

this.rows.sort(function(x, y) {
  if (x[sortBy] < y[sortBy]) {
    return -1;
  }
  if (x[sortBy] > y[sortBy]) {
    return 1;
  }
  return 0;
});

There may be minor adjustments needed for both solutions, but I hope the main concept is clear :)

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

CSS not being properly rendered on newly inserted row within table via jQuery

I'm currently working on a table that allows users to select rows, and I've implemented some CSS to highlight the selected row. The issue arises when new rows are added to the table as they do not get highlighted when selected. HTML Portion: &l ...

What is the best way to replace a CSS Background that is already marked as important?

Attempting to change the background of a website using Stylish, but encountering issues. The existing background css on the website includes an !important rule which is preventing Stylish from taking effect. Here is my code: body { background-image: n ...

Retrieve from MongoDB the items where the age is greater than 10 using the find function in the learngyoumongo

Currently working my way through the learnyoumongo tutorial and facing a challenge in part 3. The task involves a test database filled with parrots, and the objective is to retrieve the parrots whose age exceeds a specified input value. Despite using Mongo ...

Tips on reloading or refreshing a react-table component using my form component

I currently have two reactJS components set up: CustomerForm component, which includes a form along with form handling code. CustomerList component, which utilizes react-table to list the customers. Both components are fully functional and operational. ...

What is the process for "unleashing" the X Axis following the execution of chart.zoom()?

After setting the scroll strategy to setScrollStrategy(AxisScrollStrategies.progressive), I noticed that my chart was scrolling too quickly due to the fast incoming data. To address this, I decided to set a specific initial zoom level for the chart using c ...

Calculate the total value of a specific field within an array of objects

When pulling data from a csv file and assigning it to an object array named SmartPostShipments [], calculating the total number of elements in the array using the .length property is straightforward. However, I also need to calculate the sum of each field ...

Tips for organizing date columns in Bootstrap-Vue when utilizing a formatter for presentation purposes

I am working with a table containing date objects, and I have transformed them for display using the following code: { key: "date", formatter: (value, key, item) => { return moment(value).format("L"); }, sortable: true } However, this ...

Do we really need TypeScript project references when transpiling with Babel in an Electron project using Webpack?

Currently, I am in the process of setting up my project configuration and have not encountered any errors so far. However, based on my understanding of the Typescript documentation... It appears that Project references are not essential when using babel-l ...

What is the best way to conditionally render table data in React JS using a loop?

Currently, I'm working on a project with React.js and facing challenges in iterating through a data array to selectively render elements based on each data node's properties. The dataset is structured as follows: var requests = [ {"id": ...

Equal-sized tiles in Highchart treemaps

I'm attempting to display JSON data in treemaps with equal squares. I discovered that the highchart-treemap library offers four built-in algorithms - squarified, slice and dice, stripes, and strip. However, none of these algorithms provide me with the ...

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

Display solely the content within a specific Div

Currently facing an issue that needs to be resolved. I have a number of divs, each of which reveals a Span containing some text when hovered over. I've written a jQuery script for this functionality, but it currently displays all the Span elements whe ...

Leveraging gulp-data to incorporate JSON data into Nunjucks templating

I am looking to incorporate JSON data into nunjucks "set". Here's a simple example: index.html {% set divname='foo' %} {% include 'template.nunjucks' %} template.nunjucks <div class="{{divname}}"></div> Everything ...

Allowing multiple requests to be executed simultaneously in Express.js without causing any blocking issues

I am facing an issue with my Express.js website while handling post requests. The server hangs when a request triggers a query that takes several minutes to execute and respond from the database. Below is the code structure I use for database queries: Se ...

Encounter an HTTP error through Ajax triggered by an asynchronous click event using ZombieJS

I am currently working on a webpage that utilizes knockout.js and has a click handler. When the button is clicked, it triggers an AJAX request to an API server, which then responds with a contextual HTTP status result. For instance, if the user is unautho ...

The Hyperledger Sawtooth JavaScript SDK has encountered invalid submitted batches

I am currently working on integrating a hyperledger sawtooth transaction using the javascript SDK. I am following the tutorial provided here: . /* *Create the transaction header */ const createTransactionHeader = function createTransactionHeader(payloadBy ...

How to eliminate query strings from the current page's URL using JavaScript

Looking for a way to remove the querystring from the current page URL using JavaScript when a button is clicked. Can someone please provide the necessary code for this? ...

Refreshing a model using angular.js

I am attempting to reset values in the following way: $scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } However, this code ...

How can I ensure that I always have the most recent MongoDB data being transmitted from main.js to renderer.js?

Currently, I am developing a desktop application using Electron and integrating MongoDB as my data storage solution. My main objective is to automatically update the data being displayed in the front-end whenever there is a change in the MongoDB database. ...

Retrieving input value in an Android WebView

I recently attempted to extract the value of an input type and store it as a string within my Android WebView. Unfortunately, I couldn't find a straightforward solution. The snippet of code in my HTML file is as follows: <input class="input100 ...