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>