vue3中使用echarts设置tooltip的type为axis不显示的问题

95 阅读1分钟

vue3中的数据对象是用的proxy监听的,要取值需要用value等方法取出来,
解决方法:使用 markRaw 让echarts从监听对象变成普通对象!

在 Vue 3 中,markRaw 是一个用于告诉 Vue 的响应性系统不要对某个对象进行转换或追踪其响应性的函数。当你有一个对象,并且你确定你不需要它成为响应性对象时,你可以使用 markRaw 来标记它。这在一些场景中非常有用,比如当你需要集成一个第三方库或插件,并且这个库或插件的某些部分不需要是响应性的。

//useEcharts.ts
import { ref, onMounted, onBeforeMount, markRaw } from 'vue'
import * as echarts from 'echarts'
export function useChsrts(chartsRef, initalOptions) {
  const chartInstance = ref(null)
  const initCharts = async () => {
    if (chartsRef.value) {
      chartInstance.value = markRaw(echarts.init(chartsRef.value))
      const option = await initalOptions()
      chartInstance.value.setOption(option)
    }
  }
  const resizeChart = () => {
    chartInstance.value?.resize()
  }
  onMounted(() => {
    initCharts()
    window.addEventListener('resize', resizeChart)
  })
  onBeforeMount(() => {
    window.removeEventListener('resize', resizeChart)
  })
}
    <div ref="chartRef2" style="width: 100%;height: 400px;"></div>
    import { useChsrts } from '@/utils/useEcharts'
    const chartRef = ref(null);
    const setChartOption2 = async () => {
        const chartOption = reactive({
            title: {
                text: '电量统计',
            },
            legend: {
                data: []
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                },
            },
            grid: {
                bottom: '12%'
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: ["13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00"]
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value}kw'
                }
            },
            legend: {
                show: true
            },
            series: [
                {
                    name: '',
                    data: [],
                    type: 'line',
                    smooth: true
                }, {
                    name: '',
                    data: [],
                    type: 'line',
                    smooth: true
                }, {
                    name: '',
                    data: [],
                    type: 'line',
                    smooth: true
                },
            ]
        })
        const data = await chartData2();
        chartOption.legend.data = data.data.list.map((item: any) => item.name);
        data.data.list.forEach((element, index) => {
            chartOption.series[index].data = element.data;
            chartOption.series[index].name = element.name;
        });
        return chartOption
    }
    useChsrts(chartRef2, setChartOption2)