vue 中 Echarts 视图动态更新
需求:父组件中数据跟新,子组件视图更新。
思路:子组件watch监听 props数据的变更,当监听到变更时,重新加载 options配置。
所以父组件只需要更新数据,子组件来接收监听
<template>
<div>
<div :id="id" style="width:100%; height: 100%"></div>
</div>
</template>
<script>
export default {
name: 'barCharts',
props: {
id: {
type: String
},
data: {
type: Array
},
},
watch: {
data: {
handler(newValue, oldValue) {
console.log('newValue', newValue)
console.log('oldValue', oldValue)
this.initLine() // 数据更新触发
},
deep: true // 深度监听
}
},
data() {
return {}
},
methods:{
initLine() {
let option = {
...... // 视图配置项,这里简单写一些
grid: {
top: 20,
bottom: 30,
left: 0,
right: 0
},
tooltip: {
show:false
},
xAxis: {
type: 'category'
},
yAxis:{
type: 'value'
},
series:{
data:this.data, // 监听这里 更改视图
type: 'bar', // 这里举例为柱状图
}
}
let myChart = this.$echarts.init(document.getElementById('视图id,动态传入'), null, { renderer: 'svg' });
myChart.setOption(option)
}
},
mounted() {
this.initLine();
}
}
</script>
完美解决,可封装为组件,供多个同时调用,这里就不贴出来了😊

本文介绍了一个在Vue中使用Echarts实现视图动态更新的解决方案。通过子组件监听父组件传递的props数据变化,利用watch深度监听data更新,一旦数据变更则调用初始化图表的方法initLine(),更新Echarts配置并重新设置选项。这种方法允许父组件只需更新数据,子组件即可自动刷新视图,实现组件化复用。
930

被折叠的 条评论
为什么被折叠?



