123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <template>
- <div :class="className" :style="{ height: height, width: width }"></div>
- </template>
- <script>
- import echarts from 'echarts';
- require('echarts/theme/macarons'); // echarts 主题
- import resize from './mixins/resize';
- export default {
- mixins: [resize],
- props: {
- className: {
- type: String,
- default: 'chart',
- },
- width: {
- type: String,
- default: '100%',
- },
- height: {
- type: String,
- default: '350px',
- },
- chartData: {
- type: Array,
- required: true
- }
- },
- data() {
- return {
- chart: null,
- };
- },
- watch: {
- chartData: {
- deep: true,
- handler(val) {
- this.setOptions(val);
- }
- }
- },
- mounted() {
- this.$nextTick(() => {
- this.initChart();
- });
- },
- beforeDestroy() {
- if (!this.chart) {
- return;
- }
- this.chart.dispose();
- this.chart = null;
- },
- methods: {
- initChart() {
- this.chart = echarts.init(this.$el, 'macarons');
- this.setOptions(this.chartData);
- },
- setOptions(chartData) {
- // 格式化数据
- const data = chartData.map(item => ({
- value: item.counts, // 将 counts 作为 value
- name: item.typeName // 将 typeName 作为 name
- }));
- this.chart.setOption({
- tooltip: {
- trigger: 'item',
- formatter: '{a} <br/>{b} : {c} ({d}%)',
- },
- legend: {
- left: 'center',
- bottom: '10',
- data: data.map(item => item.name) // 使用提取的 typeName 作为图例
- },
- series: [
- {
- name: '会员类型', // 可以根据需要修改名称
- type: 'pie',
- radius: ['45%', '60%'], // 环形图,使用内外径
- center: ['50%', '42%'],
- data: data, // 使用提取的数据
- label: {
- show: true,
- //formatter: '{b}: {c} ({d}%)',
- formatter: '{b}: {c} 人',
- },
- labelLine: {
- show: true,
- },
- animationEasing: 'cubicInOut',
- animationDuration: 2600,
- },
- ],
- });
- },
- },
- };
- </script>
- <style scoped>
- .chart {
- width: 100%; /* 或者设置为具体的像素值 */
- height: 300px; /* 确保有高度 */
- }
- </style>
|