How to add the headers automatically from a Json in Vue 3?
How to add the headers automatically from a Json in Vue 3?
ag281198
Posts: 9Questions: 7Answers: 0
Hello I have the problem that the headers of a json that I have are not generated, the content is generated correctly but the headers are not. I get the error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'aDataSort').
Any idea how to solve it? I add screenshots of the data I'm getting in the methods I'm using.
<template>
<DataTable :data="data" :columns="tableColumns.title" :options="tableOptions"></DataTable>
</template>
<script>
import DataTable from 'datatables.net-vue3';
import DataTablesCore from 'datatables.net';
DataTable.use(DataTablesCore);
export default {
components: {
DataTable,
},
data() {
return {
data: [],
tableOptions: {
paging: true,
pageLength: 10,
ordering: true,
searching: true,
autoWidth: false,
language: {
paginate: {
first: 'First',
previous: 'Previous',
next: 'Next',
last: 'Last',
},
search: 'Filter:',
emptyTable: 'No data',
},
},
tableColumns: [],
}
},
created() {
fetch('http://localhost:3001/DataTable')
.then((response) => response.json())
.then((data) => {
this.data = data || [];
console.log('Data:', this.data);
this.headers = this.generateHeaders();
console.log('Headers:', this.headers);
this.tableColumns = this.generateColumns();
console.log('Table Columns:', this.tableColumns);
})
.catch((error) => {
console.error('Error:', error);
});
},
methods: {
generateHeaders() {
if (this.data.length > 0) {
return Object.keys(this.data[0]);
}
return [];
},
generateColumns() {
return this.headers.map((header) => ({
title: header,
data: header,
}));
},
},
}
</script>
Answers
Happy to take a look at a test case showing the issue.
Allan