As a beginner in Vue.js, I am currently working on a project that involves updating initialized arrays in the data() section of my component using the fetchData method. Below is a simplified version of the code:
<script>
import axios from 'axios';
import Footer from '@/components/Footer';
import Sidebar from '@/components/Sidebar';
import BarChart from '@/components/ChartJS/Barchart';
export default {
name: 'Dashboard',
components: {
Footer,
Sidebar,
BarChart,
},
data() {
const data1 = [];
const data2 = [];
const data3 = [];
const data4 = [];
const data5 = [];
const data6 = [];
//I need to update the data processed in the fetchData method here
const data1Count = data1.length;
const data2Count = data2.length;
const data3Count = data3.length;
const data4Count = data4.length;
const data5Count = data5.length;
const data6Count = data6.length;
return {
Cluster: {
labels: ['Data 1',
'Data 2',
'Data 3',
'Data 4',
'Data 5',
'Data 6',
],
values: [data1Count , data2Count , data3Count , data4Count , data5Count , data6Count ],
backgroundColor: ['rgba(25, 82, 105, 0.6'],
},
};
},
methods: {
fetchData() {
axios
.get('http://127.0.0.1:8000/api/dataList')
.then(response => {
this.data1 = [];
this.data2 = [];
this.data3 = [];
this.data4 = [];
this.data5 = [];
this.data6 = [];
response.data.forEach(item => {
const clusterName = item.Cluster;
switch (clusterName) {
case 'Data 1':
this.data1.push(item);
break;
case 'Data 2':
this.data2.push(item);
break;
case 'Data 3':
this.data3.push(item);
break;
case 'Data 4':
this.data4.push(item);
break;
case 'Data 5':
this.data5.push(item);
break;
case 'Data 6':
this.data6.push(item);
break;
default:
break;
}
}
);
})
.catch(error => {
console.error('Error fetching data:', error);
});
},
},
mounted() {
this.fetchData();
},
};
</script>
I am facing the challenge of ensuring that the fetchData method updates the initialized arrays (data1, data2, data3, data4, data5, and data6) directly within the data() section. The goal is to populate these arrays dynamically with API data fetched through the fetchData method so they can be easily used in the charting component.
I would greatly appreciate any advice, examples, or best practices on how to accomplish this task. Since I am new to Vue.js, step-by-step explanations or code snippets would be very helpful. Thank you for your assistance!