vuejs my chart load before fetch data
<template>
<div>
<div>
<select v-model="selectedType" @change="fetchChartData">
<option value="type1">Type 1</option>
<option value="type2">Type 2</option>
<option value="type3">Type 3</option>
</select>
</div>
<div>
<canvas ref="myChart"></canvas>
</div>
</div>
</template>
<script>
import Chart from 'chart.js/auto';
export default {
data() {
return {
selectedType: 'type1',
chartData: null,
chartInstance: null
};
},
methods: {
fetchChartData() {
// Simulating an API call with setTimeout
setTimeout(() => {
// Replace this with your actual API call to fetch chart data based on selectedType
// For demonstration purposes, generating dummy data here
const data = this.generateDummyData(this.selectedType);
this.chartData = data;
this.renderChart();
}, 1000); // Simulating a 1-second delay for API call
},
generateDummyData(type) {
// Replace this function with actual logic to fetch data from your API
// This is a placeholder for generating dummy data
const data = {
type,
labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5'],
datasets: [{
label: 'Data',
data: [30, 50, 20, 40, 60],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
};
return data;
},
renderChart() {
if (this.chartInstance) {
this.chartInstance.destroy();
}
const ctx = this.$refs.myChart.getContext('2d');
this.chartInstance = new Chart(ctx, {
type: 'bar',
data: this.chartData,
options: {
responsive: true,
maintainAspectRatio: false
}
});
}
},
mounted() {
this.fetchChartData();
}
};
</script>
<style>
/ Add your custom styles here /
</style>
Explanation:
- Template Section:
- Contains a dropdown
<select>
element to choose different types of data. A
<canvas>
element with the ref attribute set to "myChart" will be used to render the Chart.js chart.Script Section:
- Imports Chart.js library.
- Defines data properties:
selectedType
: Tracks the currently selected type from the dropdown.chartData
: Holds the fetched chart data.chartInstance
: Stores the instance of the Chart.js chart.
fetchChartData
method:- Simulates an API call with a 1-second delay using
setTimeout
. - Generates dummy data based on the selected type using
generateDummyData
method. - Updates
chartData
with the fetched data and callsrenderChart
.
- Simulates an API call with a 1-second delay using
generateDummyData
method:- Generates sample data based on the selected type.
renderChart
method:- Destroys any existing chart instance.
- Retrieves the canvas context and creates a new Chart.js instance with provided data and options.
mounted
lifecycle hook:- Calls
fetchChartData
when the component is mounted, initiating the initial chart rendering.
- Calls
Style Section:
- Reserved for custom component styles, currently empty.