vue3中动态设置echarts饼图代码
时间: 2023-11-04 11:04:37 浏览: 92
vue.js中使用echarts实现数据动态刷新功能
5星 · 资源好评率100%
以下是一个简单的例子,展示如何动态设置echarts饼图:
```html
<template>
<div class="echarts-pie-chart" ref="pieChart"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: 'EchartsPieChart',
props: {
data: {
type: Array,
default: () => []
}
},
mounted() {
this.initPieChart();
},
methods: {
initPieChart() {
const pieChart = echarts.init(this.$refs.pieChart);
const { data } = this;
const option = {
title: {
text: 'Echarts Pie Chart'
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 10,
data: data.map(item => item.name)
},
series: [
{
name: 'Pie Chart',
type: 'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: false,
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '30',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: data
}
]
};
pieChart.setOption(option);
}
},
watch: {
data() {
this.initPieChart();
}
}
}
</script>
```
在使用该组件时,可以传递一个 `data` 数组作为饼图的数据。当 `data` 发生变化时,组件会重新渲染饼图。例如:
```html
<template>
<echarts-pie-chart :data="pieChartData" />
</template>
<script>
import EchartsPieChart from '@/components/EchartsPieChart.vue';
export default {
components: {
EchartsPieChart
},
data() {
return {
pieChartData: [
{ value: 1048, name: 'Chrome' },
{ value: 735, name: 'Firefox' },
{ value: 580, name: 'Safari' },
{ value: 484, name: 'Opera' },
{ value: 300, name: 'IE' }
]
}
},
methods: {
updatePieChartData() {
this.pieChartData = [
{ value: 1000, name: 'Chrome' },
{ value: 800, name: 'Firefox' },
{ value: 600, name: 'Safari' },
{ value: 400, name: 'Opera' },
{ value: 200, name: 'IE' }
]
}
}
}
</script>
```
当调用 `updatePieChartData` 方法时,组件会重新渲染饼图,并显示新的数据。
阅读全文