Vue动态生成多个Echart图表

2,193 阅读1分钟

html

<div class="chart-dis-area">
	<div v-for="(item,index) in chartList" class="chart-item-area">
		<div class="echarts" :id="item.id"></div>
	</div>
</div>

JS

默认 chartList 是一个空数组

init() {
	let arr = [];
	for(let i = 0; i < 6; i++) {
		let item = {
			barChart: '',		// chart 对象实例
			id: 'id' + i,		// 为了标示 id 不同
		}
		arr.push(item);
	}
	this.chartList = arr;
	
	this.$nextTick(() => {
		for(let i = 0; i < this.chartList.length; i++) {
			this.chartList[i].barChart = echarts.init(document.getElementById(this.chartList[i].id));
		}
		this.getListData();		// 请求网络获取数据
	})
}

tips:这里有几个注意点。1 不能用 $refs 因为它不是响应式赋值,如果使用 ref 会出现 getAttribute undefined 错误。2 如果想要打印日志查看输出,在 nextTick 中不能使用 JSON.stringify 方法包裹数组,会出现循环引用错误