Пропсами прилетает массив с данными и массив с названием колонок, нужно сделать функционал чтобы при нажатии на название колонки таблица сортировалась в зависимости от нажатой колонки. Проблема в том, что нам постоянно прилетают разные названия колонок и разные данные, поэтому нужно сделать функцию адаптивной под разные колонки
<template>
<table>
<thead>
<tr>
<th
class="admin-table__input-wrapper"
v-for="(col, index) in columns"
:key="index"
>
<span
@click="[
col.sortBy && sortBy()
]"
:class="col.sortBy && 'sortBy'"
>
{{ col.label }}
</span>
</th>
</tr>
</thead>
<tbody>
<tr
ref="tableRow"
class="table__row"
v-for="(el, index) in data"
:key="index"
>
<td class="body-3" v-for="(col, index) in columns" :key="index">
{{ el[col.field] }}
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
name: "AdminTable",
layout: "admin",
props: {
columns: {
type: Array,
required: true,
},
data: {
type: Array,
required: true,
},
},
methods: {
sortBy() {
this.columns.forEach((col) => {
this.data.sort((a, b) => {
return a[col.field].localeCompare(b[col.field]); // Попытка сделать адаптивность под любые поля
});
});
// this.data.sort((a, b) => { Рабочий вариант, но сортировка работает только по полю fullname
// return a.fullname.localeCompare(b.fullname);
// });
},
},
};
</script>
Компонента с которой прилетают данные:
<template>
<div class="card">
<div class="card-body p-0">
<AdminTable :columns="columns" :data="trainers"/>
</div>
</div>
</template>
<script>
import AdminTable from "@/components/sections/admin-table";
export default {
layout: "admin",
components: {
AdminTable,
},
data() {
return {
trainers: [
{
id: 1312,
fullname: "Paris Stanley",
email: "Curved@gmail.com",
},
{
id: 1421,
fullname: "Layne Hensley",
email: "Pumped@gmail.com",
},
],
columns: [
{
field: "id",
label: "Id",
search: true,
sortBy: true,
},
{
field: "fullname",
label: "Full Name",
search: true,
sortBy: true,
},
{
field: "email",
label: "Email",
search: true,
sortBy: true,
},
],
};
},
};
</script>