Я пытаюсь написать логику для отображения данных в datatable. Ниже приведена таблица, которую мне нужно отобразить.
Будет только 5 столбцов Day1 to Day5. В строках, если dayName='DAY 1', тогда данные, представленные в weekDay arrayList, должны быть извлечены, как музыкальная тема (которая является значением для ключа темы в weekDay arrayList). 10 минут — это тема, время, пение — это название и так далее.
Ниже приведен формат данных -
[
{
"id": "7658dc9e-5720-4544-8780-761e1993a8a3",
"folderMapID": "d56eb3ff-dc9f-477e-82b2-ffc29a12b9f1",
"themeName": "test",
"classTime": 45,
"dayName": "DAY 2",
"isActive": true,
"weekDay": [
{
"id": "2cebd6c7-339d-4d99-a199-b1c145211272",
"position": 1,
"theme": "QA Theme One",
"themeTime": 14,
"title": "test title",
"isActive": true
}
]
},
{
"id": "8f638849-6e54-4949-b404-300aa2c8a0c0",
"folderMapID": "d56eb3ff-dc9f-477e-82b2-ffc29a12b9f1",
"themeName": "Butterfly Theme",
"classTime": 60,
"dayName": "DAY 1",
"isActive": true,
"weekDay": [
{
"id": "3796dac9-18b0-4dd4-912f-8aeeede84e6b",
"position": 1,
"theme": "Music Theme",
"themeTime": 10,
"title": "singing practice",
"isActive": true
},
{
"id": "57b8f608-d2ad-4f7b-807b-db75aa0d10a9",
"position": 2,
"theme": "Dance Theme",
"themeTime": 15,
"title": "learn dance steps",
"isActive": true
},
{
"id": "d395b047-2847-474a-a553-afbd93782092",
"position": 3,
"theme": "QA Theme One",
"themeTime": 20,
"title": "QA testing",
"isActive": true
}
]
}
]
HTML-шаблон -
<v-data-table :headers = "headers" :items = "weekScheduleList" disable-pagination
hide-default-footer>
<template v-slot:no-data>
<v-card-subtitle class = "d-flex justify-center">No Data Available</v-card-subtitle>
</template>
</v-data-table>
export default {
data () {
return {
weekScheduleList: [],
theme: '',
headers: [
{ text: 'DAY 1', value: 'theme', align: 'center', sortable: true },
{ text: 'DAY 2', value: '0', align: 'center', sortable: true },
{ text: 'DAY 3', value: '0', align: 'center', sortable: true },
{ text: 'DAY 4', value: '0', align: 'center', sortable: true },
{ text: 'DAY 5', value: '0', align: 'center', sortable: true }
],
}
},
methods: {
getWeekScheduleList: async function () {
try {
this.isLoading = true
let res = await http.get(`${CONSTANTS.API_URL}/api/get-week/${this.folderId}`)
const days = res.data
const newData = []
days.forEach(day => {
const row = {
day: day.dayName
}
day.weekDay.forEach(weekDay => {
row[weekDay.theme] = `${weekDay.theme} - ${weekDay.themeTime} mins - ${weekDay.title}`
})
newData.push(row)
})
this.weekScheduleList = newData
console.info('this.weekScheduleList :', this.weekScheduleList)
} catch (e) {
const errorMessage = (e && e.response && e.response.data.message) || e.message
this.errMsg(errorMessage)
}
},
}
Судя по вашему табличному пользовательскому интерфейсу, вам необходимо преобразовать данные API в приведенный ниже формат, где каждая строка будет содержать данные за все 5 дней.
[
{
// Day 1,
// Day 2,
// Day 3,
// Day 4,
// Day 5
},
{
// Day 1,
// Day 2,
// Day 3,
// Day 4,
// Day 5
}
]
Попробуйте приведенную ниже логику в вашей функции getWeekScheduleList
. Я добавил соответствующие комментарии, чтобы объяснить код.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel = "stylesheet">
</head>
<body>
<div id = "app">
<v-app id = "inspire">
<v-data-table
:headers = "headers"
:items = "weekScheduleList"
disable-pagination
hide-default-footer
>
</v-data-table>
</v-app>
</div>
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<script>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data() {
return {
weekScheduleList: [],
theme: "",
headers: [{
text: "DAY 1",
value: "DAY 1",
align: 'center',
sortable: true
},
{
text: "DAY 2",
value: "DAY 2",
align: 'center',
sortable: true
},
{
text: "DAY 3",
value: "DAY 3",
align: 'center',
sortable: true
},
{
text: "DAY 4",
value: "DAY 4",
align: 'center',
sortable: true
},
{
text: "DAY 5",
value: "DAY 5",
align: 'center',
sortable: true
},
],
api_data: [{
id: "7658dc9e-5720-4544-8780-761e1993a8a3",
folderMapID: "d56eb3ff-dc9f-477e-82b2-ffc29a12b9f1",
themeName: "test",
classTime: 45,
dayName: "DAY 2",
isActive: true,
weekDay: [{
id: "2cebd6c7-339d-4d99-a199-b1c145211272",
position: 1,
theme: "QA Theme One",
themeTime: 14,
title: "test title",
isActive: true,
}, ],
},
{
id: "8f638849-6e54-4949-b404-300aa2c8a0c0",
folderMapID: "d56eb3ff-dc9f-477e-82b2-ffc29a12b9f1",
themeName: "Butterfly Theme",
classTime: 60,
dayName: "DAY 1",
isActive: true,
weekDay: [{
id: "3796dac9-18b0-4dd4-912f-8aeeede84e6b",
position: 1,
theme: "Music Theme",
themeTime: 10,
title: "singing practice",
isActive: true,
},
{
id: "57b8f608-d2ad-4f7b-807b-db75aa0d10a9",
position: 2,
theme: "Dance Theme",
themeTime: 15,
title: "learn dance steps",
isActive: true,
},
{
id: "d395b047-2847-474a-a553-afbd93782092",
position: 3,
theme: "QA Theme One",
themeTime: 20,
title: "QA testing",
isActive: true,
},
],
},
],
};
},
mounted() {
this.getWeekScheduleList();
},
methods: {
getWeekScheduleList: async function() {
try {
var api_data = this.api_data;
var total_days = 5;
// Sort the api data by day's name first
api_data.sort(function(a, b) {
return a.dayName.localeCompare(b.dayName);
});
// Find the item which has maximum weedays
let max_weekday_item = this.api_data.find((item) =>
Math.max(item.weekDay.length)
);
// Outer loop for row - API data
for (
let rowIndex = 0; rowIndex < max_weekday_item.weekDay.length; rowIndex++
) {
const row = {};
// Inner loop for column
for (let colIndex = 1; colIndex <= total_days; colIndex++) {
// Find the item of respective day number
let day_item = this.api_data.find((item) => {
return item.dayName === `DAY ${colIndex}`;
});
/**
* If found then assign like this-
* row['DAY 1'] = Day 1's weekday data
* row['DAY 2'] = Day 2's weekday data
*/
if (day_item) {
row[`DAY ${colIndex}`] = day_item.weekDay[rowIndex] ?
`${day_item.weekDay[rowIndex].theme} - ${day_item.weekDay[rowIndex].themeTime} mins - ${day_item.weekDay[rowIndex].title}` :
"";
}
// Else leave it empty
else {
row[`DAY ${colIndex}`] = "";
}
}
// Push this row's data in the array
this.weekScheduleList.push(row);
}
} catch (e) {
console.error(e);
}
},
},
})
</script>
</body>
</html>
Если мы добавим еще одну строку в day1, эти данные не будут отражены.