VUE3中使用echarts,配置都正确,不出现tooltip
在vue3中使用echarts,出现个别问题,需要注意echars对象的定义,不能使用reactive或者ref定义响应式变量,要使用shallowRef ;
shallowRef 是 Vue 3 提供的一个 API,它创建一个响应式引用(ref),但只对引用的顶层属性进行响应式处理(不会深度递归转换对象内部属性)。这在处理大型对象或不需要深度响应式的场景下可以提高性能。
当在 Vue 3 中使用 ECharts 时,shallowRef 可以用来优化图表实例的存储:
import { shallowRef, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'export default {setup() {// 使用shallowRef存储图表实例const chartInstance = shallowRef(null)const chartContainer = shallowRef(null)onMounted(() => {// 初始化图表chartInstance.value = echarts.init(chartContainer.value)// 设置图表选项chartInstance.value.setOption({tooltip: {show: true,trigger: 'item'},series: [{type: 'pie',data: [{ value: 1048, name: 'Search' },{ value: 735, name: 'Direct' }]}]})})onBeforeUnmount(() => {// 组件卸载时销毁图表chartInstance.value?.dispose()})return { chartContainer }}
}
为什么在 ECharts 中使用 shallowRef
性能优化:
ECharts 实例本身是一个复杂对象,不需要深度响应式
shallowRef 避免了不必要的深度响应式转换
内存效率:
减少 Vue 响应式系统的内存开销
避免意外行为:
ECharts 实例有自己内部的状态管理,深度响应式可能导致意外行为