I want the data is sorted in ascending/descending order when I click the corresponding column. Also, I need an arrow after the column to represent the order. I’m stuck in using vue on-click build a function to sort a list and using v-bind to add an arrow. What should I do with my vue/css/html??
Here is my html
<div id="app">
<table>
<thead>
<tr></tr>
<th v-for="(header, key) in column" :key="key" v-on:click="sort(header)" v-bind:class="[sortBy === header ? sortDirection : '']">{{ 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({
sortBy: "ID",
sortDirection: "asc",
el: "#app",
data: {
arrow: {
active: true,
"text-danger": false,
},
column: {
id: "ID",
name: "Full Name",
phone: "Phone",
},
rows: [],
},
methods: {
async fetchData() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
const finalRes = await response.json();
this.rows = finalRes;
},
sort(s) {
if (this.s == this.sortBy) {
this.sortDirection = this.sortDirection === "asc" ? "desc" : "asc";
}
this.sortBy = s;
},
},
computed: {
sortedProductions: function () {
return this.products.sort((p1, p2) => {
let modifier = 1;
if (this.sortDirection === "desc") modifier = -1;
if (p1[this.sortBy] < p2[this.sortBy]) return -1 * modifier;
if (p1[this.sortBy] > p2[this.sortBy]) return 1 * modifier;
return 0;
});
},
},
mounted() {
this.fetchData();
this.sort();
this.sortedProductions();
},
});