根据echarts的官方文档formatter的回调函数的格式可以是
(params: Object|Array, ticket: string, callback: (ticket: string, html: string)) => string | HTMLElement | HTMLElement[])
那么在vue3中用createVNode和render两个函数生成的HTMLElement可以作为tooltip的返回值来使用,省去在formatter中拼接字符窜和写内联样式的麻烦
ToolTip.vue
<template>
<div class="tooltip">
<div class="tip_header">
<span :class="['icon', iconColor]"></span>
<span class="title">{{ name }}</span>
</div>
<div class="tip_body">
<div class="rate">占比: {{ rate }} %</div>
<div class="value">数量: {{ value }} 个</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const prop = defineProps({
name: {
type: String,
default: ''
},
rate: {
type: Number,
default: 0
},
value: {
type: Number,
default: 0
}
});
const iconColor = computed(() => {
let color = 'red';
if (prop.rate < 33.33) {
color = 'green';
} else if (prop.rate >= 33.33 && prop.rate < 66.66) {
color = 'yellow';
}
return color;
});
</script>
<style lang="less" scoped>
.tooltip {
width: 100px;
height: 60px;
background-color: #fff;
color: #333;
border-radius: 10px;
.tip_header {
text-align: left;
.icon {
display: inline-block;
width: 14px;
height: 14px;
border-radius: 50%;
margin-right: 8px;
&.red {
background-color: red;
}
&.yellow {
background-color: yellow;
}
&.green {
background-color: green;
}
}
}
.tip_body {
text-align: left;
}
}
</style>
formatter:
tooltip: {
formatter: (args:any) => {
// ToolTip:ToolTip.vue文件
const tip = createVNode(ToolTip, {
name: args.name,
rate: args.data.rate,
value: args.data.value
});
const mountNode = document.createElement('div');
render(tip, mountNode);
return mountNode;
}
},
页面效果: