vue中动态更新Echarts已挂载好的数据

我们在vue中使用echarts是非常方便的
像这样一个典型的使用echarts的vue文件
chart.vue

<template>
	<div id="chart"></div>
</template>

<script>
	export default {
		data() {
			return {
				deviceRec:[820, 932, 901, 934, 1290, 1330, 1320,110,1120,1900,1800,1700]
			}
		},
		mounted() {
			this.initDom()
		},
		methods: {
			initDom() {
				//基于准备好的dom,初始化echarts实例
				var myChart = this.$echarts.init(document.getElementById('chart'));
				let newData = []
				for(let i=1;i<13;i++){
					newData.push(i+'月')
				}
				let option = {
					title: {
						left: 'center',
						text: '设备接入信息',
						textStyle:{
							color: '#00CBA7'
						}
					},
					xAxis: {
						type: 'category',
						data: newData
					},
					yAxis: {
						type: 'value'
					},
					series: [{
						data: this.deviceRec,
						type: 'line',
						smooth: true,
						itemStyle:{
							color:'#00B9A1'
						},
						lineStyle:{
							width: 1,
							opacity: 0.8
						},//线条样式
						areaStyle:{
							color: {
								type: 'linear',
								x: 0,
								y: 0,
								x2: 0,
								y2: 1,
								colorStops: [{
									offset: 0, color: '#00FFDE' // 0% 处的颜色
								}, {
									offset: 1, color: '#FBFAFC' // 100% 处的颜色
								}],
								global: false // 缺省为 false
							}
						}
					}]
				}
				// 绘制图表
				myChart.setOption(option);
			},
			
		},
	}
</script>

<style scoped>
	#chart{
		width: 800px;
		height: 600px;
	}
</style>

要动态更新其中deviceRec数据时,可在chart.vue中添加一个更新数据的方法,如下代码所示:

updateData(newData){
	this.deviceRec = newData
	this.initDom()
}

父组件引入chart.vue,在父组件中调用子组件的updateData方法即可
test.vue

<chart ref="chart" />
methods: {
		changeData(data){
			//调用接口获取该年份数据
			let newData = []
			this.$refs.chart.updateData(newData)
		}
    }

你可能感兴趣的:(vue)