vue实现木马图
Vue 实现木马图(Troyan Horse Chart)
木马图(Troyan Horse Chart)是一种特殊的数据可视化图表,常用于展示分类数据的占比或对比。以下是基于 Vue 和 ECharts 的实现方法:
安装依赖
确保项目中已安装 ECharts 和 Vue-ECharts:
npm install echarts vue-echarts
基础组件封装
创建一个可复用的木马图组件(如 TroyanChart.vue):

<template>
<v-chart :option="chartOption" class="chart" />
</template>
<script>
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
LegendComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
use([
CanvasRenderer,
PieChart,
TitleComponent,
TooltipComponent,
LegendComponent
]);
export default {
components: { VChart },
props: {
data: {
type: Array,
required: true
}
},
computed: {
chartOption() {
return {
title: {
text: '木马图示例',
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 'left'
},
series: [
{
name: '占比',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: this.data
}
]
};
}
}
};
</script>
<style scoped>
.chart {
height: 400px;
width: 100%;
}
</style>
使用组件
在父组件中传入数据:
<template>
<troyan-chart :data="chartData" />
</template>
<script>
import TroyanChart from './TroyanChart.vue';
export default {
components: { TroyanChart },
data() {
return {
chartData: [
{ value: 1048, name: '分类A' },
{ value: 735, name: '分类B' },
{ value: 580, name: '分类C' },
{ value: 484, name: '分类D' }
]
};
}
};
</script>
自定义配置
-
环形大小
调整radius属性控制环形宽度:
radius: ['30%', '60%'] // 内半径30%,外半径60% -
颜色主题
通过color属性自定义色系:color: ['#c23531', '#2f4554', '#61a0a8', '#d48265'] -
交互效果
启用高亮动画:emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
注意事项
- 数据格式需为
{ value: number, name: string }[]。 - 若需动态更新数据,直接修改
data属性即可触发图表重绘。 - 移动端适配建议通过监听
resize事件调用 ECharts 实例的resize()方法。






