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

Attempting to create a child process within the renderer by triggering it with a button click

I'm currently developing an electron application where I am attempting to initiate a child node process (specifically to run a Discord.JS bot). Below is the code snippet in question: index.html: <tr> <th class="title-bar-cell" ...

MaterialUI makeStyles in NextJS causes custom css to revert back when the page is refreshed

Currently, I am working on a NextJS website with some unique styling applied through MaterialUI's makeStyles. Initially, everything looks perfect but then all the custom styling is reset on the second load. It seems to be related to the route, as it o ...

What is the best way to utilize the `Headers` iterator within a web browser?

Currently, I am attempting to utilize the Headers iterator as per the guidelines outlined in the Iterator documentation. let done = false while ( ! done ) { let result = headers.entries() if ( result.value ) { console.log(`yaay`) } ...

Display the Material UI Switch in an active state even when the "checked" value is set to false

While using Material UI Switches with Formik, I've encountered an issue. When I toggle the switch to 'enable,' it automatically sets the value in Formik to "true," and when I toggle it to 'disable,' it sets the value in Formik to " ...

Best practices for customizing v-calender in vue.js

I'm struggling with styling my calendar using the v-calendar Vue plugin. I want to customize the background of the calendar, but my code doesn't seem to be working. Can someone please help me out? Thank you in advance. HTML <v-calendar ...

The Formik form is not being populated with data from the API

While working on a functional component in ReactJS, I created a simple form using Formik. The input fields in my form are supposed to fetch data from an API when the component mounts. To achieve this, I utilized fetch and useEffect. However, after fetching ...

xhttp.load path for server-side module

I'm currently working on developing a node package and in my JavaScript code, I have the following: const calcHtml = './calc.html'; const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { ...

Tips for effectively utilizing JavaScript regex to precisely match a string before triggering the submit button

I have a form in Angular with a text input field that requires the entry of lowercase letters separated by commas, like this: c, d, e, g, a, f etc... Currently, the submit button activates as soon as any part of the input matches the required format, allo ...

I'm having trouble with my "alert()" function in Vue.js

I am new to using Vue and I am attempting to trigger an alert function when a button is clicked. However, I keep encountering the error message Uncaught ReferenceError: addTask is not defined. Below are the codes I have written: <template> ...

Is there a way to identify which specific item in a watched array has been altered in VueJS?

Imagine having an array declared in the data section like this: data() { return { myData : [{foo:2, bar:3},{foo:4,bar:5}] } } If you want to identify when the bar property of the second element changes, what should your watch function look li ...

Utilizing Angular's DomSanitizer to safely bypass security scripts

Exploring the capabilities of Angular's bypassSecurityTrust* functions has been a recent focus of mine. My objective is to have a script tag successfully execute on the current page. However, I keep encountering issues where the content gets sanitized ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

GIF Embeds with a Discord.js Bot

My bot is currently sending random gifs, but they are not embedded. I would like to send random gifs with embeds instead. How can I achieve this? Here are the codes: if (msg.author.bot) return; if (msg.content.toLowerCase() === prefix + 'xgif&ap ...

Angular code is malfunctioning and not delivering the expected results

I currently have setup the code below: var videoControllers = angular.module('videoControllers', []); videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){ $http.get('http://localho ...

How to extract data from Facebook's JSON using Javascript

I am utilizing a JavaScript API to extract Facebook comments. After receiving the JSON result below, I'm wondering how I can unpack and utilize them on my webpage? { "id": "1234567891_2823098717038_3160191", "from": { "name": "U ...

Retrieve the URL of an image located within an <li> tag within a jQuery selector item array

I am currently using a jQuery slider plugin to display images, and I am attempting to retrieve the URL of the current image when a button is clicked. The slider functions by showcasing all the image slides as list items in a continuous horizontal row. It ...

Build a child component with input fields the right way in VueJs

Utilizing vuejs, I am attempting to showcase multiple instances of a child component that contains input fields for user interaction. The parent component is set to retrieve an array of data to fill in the child components. However, since these are input ...

Using JavaScript to create delays for a group of setTimeout functions

I have a collection of items that need to be shown at various intervals using the setTimeout() function in JavaScript. What I attempted was to create a loop where, for each item, I set up a setTimeout event individually. This is the code snippet I used to ...

Error encountered when attempting to export a TypeScript class from an AngularJS module

In my application using Angular and TypeScript, I have encountered a scenario where I want to inherit a class from one module into another file: generics.ts: module app.generics{ export class BaseClass{ someMethod(): void{ alert(" ...

Capturing keydown events exclusively in the topmost layer of the HTML document

Currently, I am developing a web application that includes an underlying HTML file with some JavaScript functionality that I cannot modify. In my code, I create a layer on top of this page using CSS with z-index: 1000;. However, I am facing an issue where ...