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