我正在尝试制作一个VueJs图表,当我添加数据时, prop 正确传递到PieChart组件,但它不会反映在PieChart上。只有当我尝试在VScode上更改某些内容并保存它时,它才会突然出现。我正在尝试使PieChart组件在添加数据时直接更新自己,并在图表上显示更新后的值。
数据来自这里的API
async created() {
this.loaded = false;
try {
const response = await fetch(
'https://api2.binance.com/api/v3/ticker/24hr'
);
const data = await response.json();
await data.forEach(element => {
// console.log(element.symbol, element.lastPrice);
this.chartData.symbols = [...this.chartData.symbols, element.symbol];
// We take the volume
this.chartData.price = [...this.chartData.price, +element.lastPrice];
});
// console.log(this.chartData.symbols);
this.loaded = true;
} catch (e) {
console.error(e);
}
},
};
将数据和计算值转换为迭代值并将它们传递到组件中
chartData: {
labels: ['Vue', 'React', 'Angular'],
symbols: [],
price: [],
datasets: [
{
data: [10, 20, 30],
backgroundColor: [
'#41B883',
'#E46651',
'#20AB2E',
'#DD1B16',
'#DD26FF',
'#9ab973',
'#ff4c4c',
],
},
],
},
}),
computed: {
pairs() {
return this.chartData.symbols.map((symbol, i) => {
return {
symbol: symbol,
price: this.chartData.price[i],
};
});
},
},
饼图组件
<PieChart
:data="this.chartData.datasets[0].data"
:bgColor="this.chartData.datasets[0].backgroundColor"
:labels="this.chartData.labels"
:loaded="(this.loaded = true)"
/>
型
以及Piechart.vue文件
<template>
<Pie
v-if="loaded"
id="my-chart-id"
:options="chartOptions"
:data="chartData"
/>
</template>
<script>
import {Chart as ChartJS, ArcElement, Tooltip, Legend} from 'chart.js';
import {Pie} from 'vue-chartjs';
ChartJS.register(ArcElement, Tooltip, Legend);
export default {
name: 'PieChart',
components: {Pie},
props: ['data', 'bgColor', 'labels'],
data() {
return {
chartData: {
labels: this.labels,
datasets: [
{
data: this.data,
backgroundColor: this.bgColor,
},
],
},
chartOptions: {
responsive: true,
elements: {
arc: {
borderWidth: 0,
},
},
},
loaded: true,
};
},
methods: {},
watch: {
'chartData'(to, from) {
this.renderChart(this.chartData, this.options);
},
},
};
</script>
1条答案
按热度按时间mnowg1ta1#
我找到了答案,我在我的piechart上使用了
:key="this.chartData.labels.length"
属性,它直接更新了图表。