用vue组件重写echarts的tooltip样式

echarts
2024-02-04 09:25:56

在vue当中书写echarts的相关组件异常麻烦,常见的做法是拼接html代替,但是这样以来维护异常困难。createVNode这个内置函数来缓解这种困难。

ts 复制代码
import Tooltip from "./components/Tooltip.vue"

const option: EChartsOption = {
    tooltip: {
        trigger: 'axis',
        padding: 0,
        formatter(params: Object | Array<any>) {
            const container = document.createElement('div');
            // 先用createVNode将组件转换为vnode,再传入属性挂载到 container 容器当中。
            render(createVNode(Tooltip, { tooltips: params }), container)
            return container
        }
    },
    legend: {
        data: ['Email'],
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [
        {
            name: 'Email',
            type: 'line',
            stack: 'Total',
            data: [120, 132, 101, 134, 90, 230, 210]
        },
    ]
};

组件代码如下

vue3 复制代码
<template>
    <div class="bg">
        <div style="font-size: xx-large;text-align: center;margin-bottom: 1rem;">😀</div>
        <div v-for="tooltip in tooltips">
            <div>
                <span v-html="tooltip.marker"></span>
                <span>{{ tooltip.data }}
                    <template v-if="tooltip.data > 120">
                        👍
                    </template>
                    <template v-else>
                        👌
                    </template>
                </span>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
defineProps<{
    tooltips: {
        marker: string,
        data: number,
        dataIndex: number
    }[]
}>()
</script>
<style scoped>
.bg {
    padding: 1rem;
    box-shadow: 0 0 100px #6772FF;
    background-image: linear-gradient(315deg,#6772FF 0,#00F9E5 100%);
}
</style>