Having difficulty replicating the sorting process in Vue.js for the second time

I need assistance with implementing sorting functionality in a Vue.js table component. Currently, the sorting mechanism is working fine on the first click of the th item, but it fails to sort the items on subsequent clicks.

const columns = 
[{
name: 'Type',
key: 'type',
    sortOrder: 1,
    callback: function(item) {
      if(item.type === 'issue')
         return '<i class="fa fa-bars"></i> I-'+item.id;
      else
         return '<i class="fa fa-check-square-o"></i> R-'+item.id;
    }
},
{
name: 'Name',
key: 'name',
    sortOrder: 1
},
{
name: 'Created On',
key: 'created_at',
    sortOrder: 1
},
{
name: 'Due Date',
key: 'due_date',
    sortOrder: 1
},
{
name: 'Priority',
key: 'priority',
    sortOrder: 1
},
{
name: 'Assigned To',
key: 'email',
    sortOrder: 1
},
{
name: 'Severity',
key: 'severity',
    sortOrder: 1
},
{
name: 'Workflow',
key: 'workflow',
    sortOrder: 1
}];

const data = [{
    id: 81,
    name: "a",
    workflow: "backlog",
    created_at: "1",
    user_id: 1,
    due_date: "04:09:192016-08-06",
    severity: "se",
    priority: "1",
    type: "1",
    email: "<a href='/cdn-cgi/l/email-protection' class='__cf_email__' data-cfemail='3e4d5a585a4d7e59535f5752105d5153'>[email protected]</a>"
}, {
    id: 83,
    name: "Add files or images",
    workflow: "deployed",
    created_at: "2016-08-01 03:09:19",
    user_id: 5,
    due_date: "2016-08-06",
    severity: "Major",
    priority: "1",
    type: "issue",
    email: "<a href='/cdn-cgi/l/email-protection' class='__cf_email__' data-cfemail='fd89988e89bd9a909c9491d39e9290'>[email protected]</a>"
}];
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.17/vue.js'></script>
<script src='https://cdn.jsdelivr.net/lodash/4/lodash.min.js'></script>
<!DOCTYPE html>
<html>

  <head>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css' />
    <link href='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css'
  </head>

  <body>
   
<script type='text/x-template' id='testnetic-table'>
<input type='text' v-model='searchKey'>
<table class='table table-hover table-light table-responsive'>
<thead>
<tr>
<th v-for='item in columns'
 @click='sortBy($index)'>
 {{ item.name | capitalize}}
   <i class='fa' :class='item.sortOrder > 0 ? 'fa-sort-desc' : 'fa-sort-asc''></i>
</th>
</tr>
</thead>
<tbody>
<tr v-for='item in data
                | filterBy searchKey
                | orderBy sortKey columns[$index].sortOrder'
              >
              <td v-for='cell in columns'> 
                {{{ display(item,cell.key,$index)}}}
              </td>
            </tr>
</tbody>
</table>
</script>

<div id='test'>
  <testnetic-table
  :columns='columns'
  :data='data'
  ></testnetic-table>
</div>

  </body>
 
</html>

Answer №1

In order for the sorting functionality to work properly, it is essential to have a sortOrder defined at the same level as the sortKey. When a column header is clicked, the following steps need to be taken:

  1. If the clicked column is already the sortKey, reverse the sortOrder for that specific column (if not, set it as the sortKey)
  2. Regardless of the previous step, update the sortOrder to match the column's current sortOrder value

var columns = [{...}];
var data = [{...}];

Vue.config.debug = true;

Vue.component('testnetic-table', {
  template: '#testnetic-table',
  props: ['data', 'columns'],
  data: function() {...},
  methods: {
    sortBy: function(index) {...},
    display: function(item, key, index) {...}
  }
});

new Vue({
  el: '#test',
  data: function() {...}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" />
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css"> </head>

  <body>

    <script type="text/x-template" id="testnetic-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

Extracting CSS data and storing it in a SQL database

Hello there, I've created a div using CSS like this: echo '#'. $pess2['naam'] .' { width: 190px; height: 90px; padding: 0.5em; float: left; left:'. $pess2['left'] .'px; top:'. $pess2['top'] ...

Parsing DXF files using only plain JavaScript

Currently, I am immersed in a CNC project and aiming to convert DXF files into objects using JS. Initially, I attempted using SVGs but the results were not as expected - instead of shapes, the drawings exported as lines (e.g., a square appearing as four se ...

What are the proper methods for accurately testing vuex state and mutations?

Can someone guide me on how to properly test mutations and state? I have a modal window component that is rendered when the showModal property in the state is true. There is an event triggering a mutation that changes this property. How can I verify that a ...

The Star Rating System fails to update accurately after hiding the Radio Buttons

I followed a tutorial to set up a Star Rating System Everything was working fine on the SHOW PAGE and the INDEX PAGE until I decided to hide the Radio Buttons and use the corresponding labels to submit the value. I encountered an issue where the JavaScrip ...

Quickly Share Documents within a Folder

I currently have a server set up with the following file structure: - index.js /client -index.html -about.html -signup.html -style.css Within the index.js file, I have implemented an express server. When the user navigates to /, it should display the ...

A comprehensive guide to utilizing Vue for navigating between various pages and showcasing their corresponding titles and text

I am currently developing a blog website using vue.js. My current challenge is as follows: The website has two main pages - one for displaying all the blogs and another for viewing a specific blog post. I am utilizing vuex to manage the state of my applic ...

Initially display checkboxes for selecting items using a custom row template in V-data-table

I have implemented a custom template for each row in a v-data-table, and I am encountering an issue with checkboxes. When using :value="item", all checkboxes are initially checked, which is not the behavior I want. I am unsure of how to approac ...

The Controller's ActionResult methods are not successfully collecting form data sent through an ajax request

I'm facing an issue with my purchase form where the purchase_return object in the controller is not receiving any data. It seems to be getting productId as 0 and productNm as null. Can someone help me figure out what's causing this issue? Here&a ...

Data in LocalStorage will not be set until the Vue.js component is mounted

Enhancing user experience, I am implementing a shopping cart feature using localStorage. By triggering an event with EventBus from ProductCard.vue, I am globally storing data to localStorage. Subsequently, I retrieve these values back in ProductCard.vue. ...

Using AngularJS to show/hide elements within a colgroup tag

Looking to create a dynamic table allowing users to hide certain columns. Wondering if it's possible to use ng-show with colgroup or col tags instead of adding ngshow to each cell individually. Struggling to make it work... <colgroup ng-repeat="mt ...

The ngIf statement in the template isn't functioning properly after a refresh; instead, it is causing a redirection to the homepage

I've been developing with Angular 7, trying to display a <div> ... </div> based on multiple values that I declared as : Boolean = false; in the .ts file. These values are updated in ngOnInit, but for some reason, the page keeps redirecting ...

Sharing data between two components on the same level in Vue.js

I have a situation where I need to transfer data from one component1 to another component2. I am not utilizing vuex or router for this task. The component tree looks like this: -Parent --Component1 --Component2 In the first component1, I am sending an ...

What is the best way to send a promise back from my service to my controller?

While I have posed this question in various forms, I now find myself stuck with a piece of code that contains an elusive bug. My Angular service looks like this: .service("lookupDataService", [ '$q', '$http', '$timeout&ap ...

Retrieve the concealed method's name within the immediately invoked function expression (IIFE

This Meteor sever code has a private method called printFuncName within an IIFE. However, when this method is invoked from a public method, it results in the following error: TypeError: Cannot read property 'name' of null I am curious to unde ...

Guide on waiting for AWS assumeRole before proceeding with defining the module

I'm currently working on a module that needs to export functions and variables, but before it can do that, it must switch user roles. Here is the code snippet I've come up with. What I need is for the anonymous async function to execute first, an ...

Merge requirejs modules using build script

I am attempting to merge and compress require modules into a single file. For instance, if I have a file named article.js with the following content: define(["jquery","flexslider","share_div"],function(){}); I wish for all these dependencies to be merge ...

Securing API from unauthorized direct access

Currently, my backend and frontend are separate but hosted on the same server (although this setup may change in the future). The backend functions as an api and is built using Laravel, while the frontend uses Nuxt (Vue). I want to restrict access to the ...

What is the most effective way to compare two arrays of objects in JavaScript?

I'm working on a function that needs to return an array of elements based on certain filters. Here is the code for the function: filter_getCustomFilterItems(filterNameToSearch: string, appliedFilters: Array<any>) { let tempFilterArray = []; ...

Ajax/PHP - unrecognized value in autofill

I have implemented this particular example to execute an ajax data query from a MySQL database, which returns a table. Currently, this setup functions correctly when text is manually entered into the input form. Example: https://i.sstatic.net/TTgLz.jpg T ...

JavaScript's speciality - altering the Jquery fade in and fade out effect on Firefox browsers

Utilizing Jquery, I implemented a feature on a table where moving the mouse over a row changes its color. The Javascript code was specifically designed for IE7 and works flawlessly there. However, when tested in Firefox, the text fades along with the backg ...