vue3 集成 echarts 最大的坑就是出现了,reactive 的数据 刷新了,但图表缺不会刷新,查了很多资料,试了很多方式都没效果,最后测试出来解决方法很简单:
核心代码:
// 省略非核心代码.......
const init = () => {
chart.value = globalProperties?.echarts.init(pieChartRef.value)
chart.value.setOption(option)
}
watch(
() => props.data,
() => {
// 数据变化时,重新对series里面的 data 赋值即可
option.series[0].data= top10()
chart.value.setOption(option)
}
)
onMounted(() => {
init()
addEventListener('resize', resize)
})
附上 TSX 整个页面参考
import {defineComponent, getCurrentInstance, onBeforeUnmount, onMounted, PropType, ref, watch} from 'vue'
import type { Ref } from 'vue'
import {ECharts, throttle} from "echarts";
import {useI18n} from "vue-i18n";
import {EChartsType} from "echarts/types/dist/echarts";
const props = {
height: {
type: [String, Number] as PropType,
default: 590
},
width: {
type: [String, Number] as PropType,
default: '100%'
},
data: {
type: Array as PropType>
}
}
const PieChart = defineComponent({
name: 'PieChart',
props,
setup(props) {
const pieChartRef: Ref = ref(null)
const top10 = () => {
return props.data.length>=10 ? props.data.slice(0,10) : props.data
}
const option = {
title: {
text: '分组聚合 Top 10',
left: 'center',
textStyle: {
color:'white'
},
},
tooltip: {
trigger: 'item',
backgroundColor: '#fff'
},
legend: {
bottom: '0%',
left: 'center',
textStyle:{
fontSize: 16,
color: 'white',
fontWeight: 'bold'
}
},
series: [
{
type: 'pie',
radius: ['35%', '60%'],
center: ['50%', '40%'],
avoidLabelOverlap: false,
emphasis: {
label: {
show: true,
fontSize: 30,
fontWeight: 'bolder',
color: 'white'
}
},
label: {
show: false,
position: 'center'
},
labelLine: {
show: false
},
data: top10()
}
]
}
const globalProperties = getCurrentInstance()?.appContext.config.globalProperties
let chart:Ref = ref(null)
const init = () => {
chart.value = globalProperties?.echarts.init(pieChartRef.value)
chart.value.setOption(option)
}
const resize = throttle(() => {
chart && chart.value.resize()
}, 20)
watch(
() => props.data,
() => {
// 数据变化时,重新对series里面的 data 赋值即可
option.series[0].data= top10()
chart.value.setOption(option)
}
)
onMounted(() => {
init()
addEventListener('resize', resize)
})
return { pieChartRef }
},
render() {
const { height, width } = this
return (
)
}
})
export default PieChart