Vue.js does not support sorting columns

In this specific codepen example, I have created a Vue table that allows for sorting by clicking on the column name. Although I can successfully retrieve the column name in the function and log it to the console, the columns are not sorting as expected. What could be causing this issue? Your insights would be greatly appreciated.

var table = new Vue({
  el: '#table',
  data: {
    ascending: false,
    sortColumn: '',
    rows: [{
        id: 1,
        name: "Red"
      },
      {
        id: 2,
        name: "Blue"
      },
      {
        id: 3,
        name: "Green"
      },
      {
        id: 4,
        name: "Brown"
      },
      {
        id: 5,
        name: "Grey"
      },
      {
        id: 6,
        name: "Pink"
      }
    ]
  },
  methods: {
    "sortTable": function sortTable(col) {
      console.log(col)
      if (this.sortColumn === col) {
        this.ascending = !this.ascending;
      } else {
        this.ascending = true;
        this.sortColumn = col;
      }

      var ascending = this.ascending;

      this.rows.sort(function(a, b) {
        if (a[col] > b[col]) {
          return ascending ? 1 : -1
        } else if (a[col] < b[col]) {
          return ascending ? -1 : 1
        }
        return 0;
      })
    }
  },
  computed: {
    "columns": function columns() {
      if (this.rows.length == 0) {
        return [];
      }
      return Object.keys(this.rows[0])
    }
  }
});
table {
  font-family: 'Open Sans', sans-serif;
  width: 750px;
  border-collapse: collapse;
  border: 3px solid #44475C;
  margin: 10px 10px 0 10px;
}

table th {
  text-transform: uppercase;
  text-align: left;
  background: #696969;
  color: #FFF;
  cursor: pointer;
  padding: 8px;
  min-width: 30px;
}

table th:hover {
  background: #A9A9A9;
}

table td {
  text-align: left;
  padding: 8px;
  border-right: 2px solid #696969;
}

table td:last-child {
  border-right: none;
}

table tbody tr:nth-child(2n) td {
  background: #D3D3D3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<table id="table">
  <thead>
    <tr>
      <th v-on:click="sortTable('ID')">ID</th>
      <th v-on:click="sortTable('Name')">Name</th>
  </thead>
  <tbody>
    <tr v-for="row in rows">
      <td>{{row.id}}</td>
      <td>{{row.name}}</td>
    </tr>
  </tbody>
</table>

Answer №1

Remember, javascript is case sensitive!

<th v-on:click="sortTable('id')">ID</th>
<th v-on:click="sortTable('name')">Name</th>

Take note of using id and name as arguments for the sortTable function - these are the keys in the table (not ID and Name)

var table = new Vue({
  el: '#table',
  data: {
    ascending: false,
    sortColumn: '',
    rows: [{
        id: 1,
        name: "Red"
      },
      {
        id: 2,
        name: "Blue"
      },
      {
        id: 3,
        name: "Green"
      },
      {
        id: 4,
        name: "Brown"
      },
      {
        id: 5,
        name: "Grey"
      },
      {
        id: 6,
        name: "Pink"
      }
    ]
  },
  methods: {
    "sortTable": function sortTable(col) {
      console.log(col)
      if (this.sortColumn === col) {
        this.ascending = !this.ascending;
      } else {
        this.ascending = true;
        this.sortColumn = col;
      }

      var ascending = this.ascending;

      this.rows.sort(function(a, b) {
        if (a[col] > b[col]) {
          return ascending ? 1 : -1
        } else if (a[col] < b[col]) {
          return ascending ? -1 : 1
        }
        return 0;
      })
    }
  },
  computed: {
    "columns": function columns() {
      if (this.rows.length == 0) {
        return [];
      }
      return Object.keys(this.rows[0])
    }
  }
});
table {
  font-family: 'Open Sans', sans-serif;
  width: 750px;
  border-collapse: collapse;
  border: 3px solid #44475C;
  margin: 10px 10px 0 10px;
}

table th {
  text-transform: uppercase;
  text-align: left;
  background: #696969;
  color: #FFF;
  cursor: pointer;
  padding: 8px;
  min-width: 30px;
}

table th:hover {
  background: #A9A9A9;
}

table td {
  text-align: left;
  padding: 8px;
  border-right: 2px solid #696969;
}

table td:last-child {
  border-right: none;
}

table tbody tr:nth-child(2n) td {
  background: #D3D3D3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<table id="table">
  <thead>
    <tr>
      <th v-on:click="sortTable('id')">ID</th>
      <th v-on:click="sortTable('name')">Name</th>
  </thead>
  <tbody>
    <tr v-for="row in rows">
      <td>{{row.id}}</td>
      <td>{{row.name}}</td>
    </tr>
  </tbody>
</table>

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

An issue arises when attempting to fetch data using next.js: a TypeError occurs indicating that

I'm currently working on setting up a next.js website integrated with strapi, but I've encountered an issue with my fetch request. Oddly enough, when I test the request using Postman, the data is successfully returned, indicating that the endpoin ...

Whenever a user logs in or logs out from the child component, the app.js is not being re-rendered

I'm having trouble figuring out how to re-render the app.js function. It loads initially, but when I click the login or logout button, I need to call a function from the helper again to check the user status. Here is the code snippet for App.js: impor ...

The width and height properties in the element's style are not functioning as expected

let divElement = document.createElement("div"); divElement.style.width = 400; divElement.style.height = 400; divElement.style.backgroundColor = "red"; // num : 1 divElement.innerText = "Hello World "; // num : 2 document.body.append(divElement); // Af ...

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

Unable to access component data while inside a v-for loop scope

I recently started using Vue and I'm having trouble accessing my component data within a v-for loop. After implementing the code below, I encountered this error message. TypeError: Cannot read property 'whatever' of undefined at eva ...

Calling this.$refs.upload.submit() is not providing the expected response from Element-UI

Currently working with element-ui and attempting to upload a file using the following code: this.$refs.upload.submit(); Is there a way to retrieve the response from this.$refs.upload.submit();? I have attempted the following: .then(response => { t ...

Using Laravel along with Inertia.js and Vue, we can easily determine whether a user is logged in

I am currently using Laravel along with Inertia.js for my project implementation. I am facing an issue where I want to display a div element containing some user details in the navbar only if the user is logged in. However, the div should not appear if the ...

Is it feasible to utilize Google Calendar API for JavaScript through npm install? Alternatively, can the Google Calendar API be utilized for Node.js in the browser within Next.js?

Looking to integrate the Google Calendar API as a library in your Next.js project without using _document.tsx? I have explored two potential approaches for achieving this: Utilize the google calendar api for JavaScript by installing it via npm Use the goo ...

What causes jquery height and javascript height to both be returned as 0?

I'm facing an issue with a visible div on my screen - despite being visible, its height always returns as 0. I've attempted various jQuery and JavaScript methods to retrieve the height, but it consistently shows as 0. Here's the structure of ...

Having trouble with your jQuery AJAX function not receiving the text returned from your PHP file?

After extensive searching, I have come across several individuals facing the same issue as me, but unfortunately, none of them seem to have found a solution. The problem at hand is that PHP is not providing any data to the AJAX function. When I try to dis ...

What is the method to execute jQuery code after the completion of a fade out effect?

I am attempting to fade out a div upon click while also adjusting some CSS properties. The problem I am encountering is that the CSS properties change during the fade out transition, instead of after it has completed. I would like the values to change onc ...

What is the best way to zoom in on an image and make it move off the screen as I scroll through my webpage?

I am working on a website design where I would like to implement an image zoom effect as the user scrolls down. Additionally, I want the image to move to either the left or right side of the screen as it goes out of view when scrolling to the bottom. While ...

Preventing an event from bubbling up to its parent in a jQuery Ajax call: A step-by-step guide

I am working on a page that showcases a tree list using unordered lists. Each li element with children triggers an ajax call to fetch those children and display them as another ul/li combination, which is functioning correctly. However, the problem arise ...

Is there a more efficient method for implementing server side rendering in a Next.js application?

Currently, I am implementing server-side rendering in my Next.js application. This specific component is responsible for returning HTML content. I'm wondering if there are more efficient methods available? import Feature from 'components/home/Fea ...

Reloading a page will display [object CSSStyleDeclaration]

Upon editing content and saving changes, instead of displaying my updated content when refreshing the page, it shows [object CSSStyleDeclaration]. function newElement() { let li = document.createElement("li"); let inputvalue = document.querySelector ...

Exploring the benefits of using Styled Components for creating global styles in React and Next.js: Should you opt for a mix of CSS files and Styled Components?

Recently, I implemented Styled Components in my Next.js app by following the guidelines from Styled Components. Currently, I am delving into the realm of best practices for managing global styles with Styled Components. The first aspect that piques my curi ...

Is there a way to retrieve the current state of a Material UI component in a React functional component without needing to trigger an event by clicking on

Seeking a way to retrieve current values of Material Ui components without the need to click on any event after page reloads or DOM changes. These values are pulled from a database. My goal is to confirm whether the values have been updated or not by chec ...

jQuery and HTML: Need help enabling an <input> or <select> element?

Currently, I am using Mozilla Firefox 14.0.1 and Google Chrome 20.0.1132.57 (which I believe is the latest version). The code I am working with looks like this: http://jsfiddle.net/SVtDj/ Here is what I am trying to accomplish: Type something into inpu ...

Select component with nested checkboxes for multilevel dropdown

I am interested in developing nested dropdowns with checkboxes, similar to the example shown in this image: Image 1 Is there a way to achieve this functionality using React? I have not been able to find any specific library that allows for this implement ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...