共计 2205 个字符,预计需要花费 6 分钟才能阅读完成。
一、问题
使用 vue3 写页面,引入一个 echarts 图,父组件数据改变,图表没有重新渲染。
二、目标效果图
三、解决(数据变了,图表不变化)
只需要 2 步:
1、echarts 图组件监听数据(数据改变,重新渲染)
watch(
() => props.chartData,
() => {
echart.dispose(document.getElementById('LineBar'))
initChart()
}
)
2、在使用 setOption() 方法之前,重新给 option 中的数据赋值即可,代码如下:
let initChart = () => {
let Echarts = echarts.init(document.getElementById('LineBar'))
option.value.xAxis.data = props.chartData.xAxisData
option.value.series[0].data = props.chartData.data
Echarts.setOption(option.value)
window.addEventListener(
'resize',
(window.onresize = () => {
Echarts.resize()
})
)
}
注意:父组件正常调接口 传值即可
解决警告 There is a chart instance already initialized on the dom.
echart.dispose(document.getElementById('LineBar'))
解决警告 Instance ec_1680155339347 has been disposed
不要使用以下写法:(暂时不清楚具体原因)
window.addEventListener(
'resize',
(window.onresize = () => {
Echarts.resize()
})
)
改为这样写法:
window.addEventListener('resize', onResize(Echarts))
let onResize = (Echarts) => {
window.onresize = () => {
Echarts.resize()
}
}
四、Echarts 子组件 完整代码
template>
div id="LineBar">/div>
/template>
script name="LineBar" setup>
import { onMounted, defineProps, watch } from 'vue'
import * as echarts from 'echarts'
const props = defineProps({
chartData: {
type: Object,
required: true
}
})
watch(
() => props.chartData,
() => {
echart.dispose(document.getElementById('LineBar'))
initChart()
}
)
let option = ref({
tooltip: {
trigger: 'axis'
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
boundaryGap: false,
data: props.chartData.xAxisData
},
yAxis: {
type: 'value'
},
series: [
{
name: 'ddd',
type: 'line',
smooth: true,
data: props.chartData.data,
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: 'rgba(46, 121, 255, 0.2)'
},
{
offset: 1,
color: 'rgba(46, 121, 255, 0.0001)'
}
]
}
},
color: '#2E79FF',
lineStyle: {
color: {
colorStops: [
{
offset: 0,
color: '#8477FF'
},
{
offset: 1,
color: '#5CCAFF'
}
]
},
width: 2,
shadowOffsetY: 12,
shadowColor: 'rgba(59, 138, 254, 0.1)'
}
}
]
})
let echart = echarts
onMounted(() => {
initChart()
})
let initChart = () => {
let Echarts = echarts.init(document.getElementById('LineBar'))
option.value.xAxis.data = props.chartData.xAxisData
option.value.series[0].data = props.chartData.data
Echarts.setOption(option.value)
window.addEventListener('resize', onResize(Echarts))
}
let onResize = (Echarts) => {
window.onresize = () => {
Echarts.resize()
}
}
/script>
style scoped>/style>
原文地址: Vue3 父组件数据改变 Echarts 子组件图表没有变化
正文完