在vue项目中echarts父子组件异步传值,解决数据更新,echarts页面不更新问题 | 您所在的位置:网站首页 › echarts网页空白 › 在vue项目中echarts父子组件异步传值,解决数据更新,echarts页面不更新问题 |
在使用echarts进行数据展示的时候,遇到了一个问题。echarts图表是作为子组件进行展示的,需要父组件发送请求并获取到返回数据后再传给子组件进行数据展示,但是由于子组件比父组件先渲染,所以就会导致子组件获取不到父组件传递的数据。针对这个问题,可以使用vue中的watch监视来解决。 首先,在父组件中引入子组件并注册 import bar from './bar.vue' components:{ bar } 其次,将数据传递给子组件
在子组件中,通过props接收父组件的数据,并通过watch监听 props: { srcData: { type: Array, require: true, default: () => [] } } watch:{ srcData(val){ // 监测父组件传过来的数据进行处理成柱形echarts需要的格式 const ips = [] const nums = [] const newArr = val if (newArr.length > 0) { newArr.forEach(item => { ips.push(item.ip) nums.push(item.num) }) this.scourceIpEchart(nums, ips, '') } else { this.scourceIpEchart([], [], '') }
} }, methods:{ 渲染图表 方法 // 源IP地址echarts 渲染的echarts在组件种渲染 接口数组由父组件传入 scourceIpEchart(series, dataX, unit) { // 检测是否已经存在echarts实例,如果不存在,则不再去初始化 this.scourceIp = echarts.getInstanceByDom( this.$refs.scourceIp ) // 如果为空 则正常进行渲染 反之 不再进行初始化 if (this.scourceIp == null) { this.scourceIp = echarts.init(this.$refs.scourceIp) } this.scourceIp.clear(this.scourceIpOption) // 清空当前画布所有数据 this.scourceIpOption = { tooltip: { trigger: 'item', position: 'top', axisPointer: { type: 'none' }, appendToBody: true }, grid: { left: '4%', right: '4%', bottom: '10%', height: '80%', containLabel: true }, yAxis: { type: 'value', minInterval: 1, // 最小单位是1 axisLabel: { formatter: '{value}' + unit, color: '#989898', interval: 0 }, // 整条y轴 axisLine: { show: true, lineStyle: { type: 'solid', color: '#DDDDDD' } } }, xAxis: { type: 'category', data: dataX, axisLine: { show: true, lineStyle: { type: 'solid', color: '#DDDDDD' } }, axisTick: { 'show': true }, axisLabel: { color: '#989898', rotate: 40, interval: 0 } }, color: ['#639EFF'], series: [ { name: '', type: 'bar', barWidth: 30, barMinHeight: 5, // 柱形的高度最小展示 data: series } ] } this.scourceIp.setOption(this.scourceIpOption) }, }
|
CopyRight 2018-2019 实验室设备网 版权所有 |