复现
封装了一个函数,用来管理echart实体的一些状态和操作
import { ref } from "vue"
import * as echarts from "echarts"
export function useChart() {
const chartRef = ref(null)
const chartInstance = ref(null)
function init() {
if(chartRef.value === null) {
throw new Error("没有获取到dom实体")
}
const existEchartInstance = echarts.getInstanceByDom(chartRef.value)
if(existEchartInstance) {
existEchartInstance.dispose()
}
chartInstance.value = echarts.init(chartRef.value)
}
function setOption(option) {
if(chartInstance.value === null) {
throw new Error("没有初始化echarts实例")
}
chartInstance.value.setOption(option)
}
function resize() {
if(chartInstance.value === null) {
throw new Error("没有初始化echarts实例")
}
chartInstance.value.resize()
}
return {
chartRef,
chartInstance,
init,
setOption,
resize,
}
}
绘制一个简单的带有的滚动轴的折线图
<script setup>
import { useChart } from '@/hooks/useChart';
import { onMounted } from 'vue';
const chartManage = useChart()
const option = {
dataZoom: [
{
type: 'slider', // 使用滑动条型 dataZoom 组件
show: true, // 显示缩略图
start: 0, // 缩略图开始位置
end: 100, // 缩略图结束位置
bottom: 15, // 缩略图距离容器底部的距离
height: 20, // 缩略图组件的高度
dataBackground: {
lineStyle: {
opacity: 0
},
areaStyle: {
opacity: 0
}
},
selectedDataBackground: {
lineStyle: {
opacity: 0
},
areaStyle: {
opacity: 0
}
}
}
],
grid: {
top: 65,
bottom: 65,
left: 55,
right: 35
},
tooltip: {
show: true,
trigger: 'axis',
enterable: true
},
legend: {
right: 10, // 距离容器右侧的距离
top: 10, // 距离容器顶部的距离
},
xAxis: [
{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Series 1',
type: 'line',
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
};
onMounted(() => {
chartManage.init()
chartManage.setOption(option)
})
</script>
<template>
<div class="chart" :ref="chartManage.chartRef"></div>
</template>
<style scoped>
.chart {
height: 100%;
}
</style>
但是当我滚动底部的滑轮的时候,会报错
echarts.init返回的示例不要使用vue的ref或者reactive来接收