Alpine js data refresh does not apply
I have a simple HTML table build with alpine, and I wanted to apply a simple sorting for data on the click of a table header element.
<div x-data="{
tableHeaders: ['first', 'second', 'third'],
data: [[1,2,3], [2,3,1], [3,1,2]],
sortData(categ){
var index = this.tableHeaders.indexOf(categ);
this.data.sort((a, b) => {
let x = a[index];
let y = b[index];
return x < y ? -1 : x > y ? 1: 0;
});
console.log(categ, index, this.data);
}
}">
<table>
<thead>
<template x-for="header in tableHeaders">
<th @click="sortData(header);" x-text="header"></th>
</template>
</thead>
<tbody >
开发者_如何学JAVA <template x-for="line in data">
<tr>
<template x-for="col in line">
<td x-html="col"></td>
</template>
</tr>
</template>
</tbody>
</table>
</div>
I get output like expected:
first 0 [[1, 2, 3], [2, 3, 1], [ 3, 1, 2 ] ]
second 1 [ [ 3, 1, 2 ], [ 1, 2, 3 ], [ 2, 3, 1 ] ]
third 2 [ [ 2, 3, 1 ], [ 3, 1, 2 ], [ 1, 2, 3 ] ]
But the table order does not change and the x-for directive doesn't get triggered. What am I missing?
I got the solution and thought, it might be helpful for the next one encountering a similar problem. Maybe someone with more knowledge can share the reason for this. if you update data in place, it doesn't trigger the update, but if you set it again, it does! here is just the updated function which works:
<html>
<head>
<script src="https://unpkg.com/alpinejs@3.10.5/dist/cdn.min.js" defer></script>
</head>
<body>
<div x-data="{
tableHeaders: ['first', 'second', 'third'],
data: [[1,2,3], [2,3,1], [3,1,2]],
sortData(categ){
var index = this.tableHeaders.indexOf(categ);
this.data = this.data.sort((a, b) => {
let x = a[index];
let y = b[index];
return x < y ? -1 : x > y ? 1: 0;
});
}
}">
<table>
<thead>
<template x-for="header in tableHeaders">
<th @click="sortData(header);" x-text="header"></th>
</template>
</thead>
<tbody >
<template x-for="line in data">
<tr>
<template x-for="col in line">
<td x-html="col"></td>
</template>
</tr>
</template>
</tbody>
</table>
</div>
精彩评论