vue3 集成 echarts 最大的坑就是出现了,reactive 的数据 刷新了,但图表缺不会刷新,查了很多资料,试了很多方式都没效果,最后测试出来解决方法很简单:
核心代码:文章来源:https://www.toymoban.com/news/detail-635190.html
// 省略非核心代码.......
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 整个页面参考文章来源地址https://www.toymoban.com/news/detail-635190.html
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<string | number>,
default: 590
},
width: {
type: [String, Number] as PropType<string | number>,
default: '100%'
},
data: {
type: Array as PropType<Array<any>>
}
}
const PieChart = defineComponent({
name: 'PieChart',
props,
setup(props) {
const pieChartRef: Ref<HTMLDivElement | null> = 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<ECharts | null> = 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 (
<div
ref='pieChartRef'
id={'myChart'}
style={{
height: "300px",
width: typeof width === 'number' ? width + 'px' : width
}}
>
</div>
)
}
})
export default PieChart
到了这里,关于解决vue3集成echarts数据刷新后图表不刷新问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!