Build a generic Data Table component with sorting.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
<template>
<table>
<thead>
<tr>
<th v-for="col in columns" @click="sort(col.key)">{{ col.label }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in sortedData" :key="row.id">
<td v-for="col in columns">{{ row[col.key] }}</td>
</tr>
</tbody>
</table>
</template>
<script setup>
import { ref, computed } from 'vue';
const props = defineProps({ data: Array, columns: Array });
const sortKey = ref('');
const sortOrder = ref(1);
const sort = (key) => {
if (sortKey.value === key) sortOrder.value *= -1;
else { sortKey.value = key; sortOrder.value = 1; }
};
const sortedData = computed(() => {
if (!sortKey.value) return props.data;
return [...props.data].sort((a, b) => {
return (a[sortKey.value] > b[sortKey.value] ? 1 : -1) * sortOrder.value;
});
});
</script>