Initialize failed: invalid dom.
dom对象还未被创建
1.使用mounted生命周期
2.用this.$nextTick(()=>{})3.setTimeout(()=>{})
There is a chart instance already initialized on the dom.
其实dom已经存在了,但是我们在每次数据发生改变的时间都重新进行了一次渲染,导致出现警告
let myChart = echarts.getInstanceByDom(this.$refs['picChart'])
if (myChart == null) {
myChart = echarts.init(this.$refs['picChart']);
}
示例:
import * as echarts from 'echart5/core' import { TitleComponent, TooltipComponent, LegendComponent } from 'echart5/components' import { PieChart } from 'echart5/charts' import { LabelLayout } from 'echart5/features' import { CanvasRenderer } from 'echart5/renderers'mounted() { echarts.use([ TitleComponent, TooltipComponent, LegendComponent, PieChart, CanvasRenderer, LabelLayout ])this.loadData() },loadChart() { let myChart = echarts.getInstanceByDom(this.$refs['picChart']) if (myChart == null) { myChart = echarts.init(this.$refs['picChart']); } const dataName = [] let total = 0 this.dataList.forEach(x => { dataName.push(x.name) total += parseFloat(x.value) }) const option = { legend: { icon: 'circle', orient: 'vertical', right: '0', top: 'center', padding: [0, 20, 0, 0], // 可设定图例[距上方距离,距右方距离,距下方距离,距左方距离] formatter: (name) => { let total = 0 let target const value = this.dataList.filter(x => x.name == name)[0].value for (let i = 0, l = this.dataList.length; i < l; i++) { total += this.dataList[i].value if (this.dataList[i].name == name) { target = this.dataList[i].value } } const arr = [ '{name|' + name + '}{value|' + value + '}{percentage|' + (target > 0 ? ((target / total) * 100).toFixed(2) : 0) + '%}' ] return arr.join('\n') }, textStyle: { rich: { name: { fontSize: 20, align: 'left', padding: [20, 0, 20, 20], lineHeight: 40, width: 100 }, value: { fontSize: 20, align: 'right', padding: [20, 0, 20, 20] }, percentage: { fontSize: 20, align: 'right', padding: [20, 0, 20, 20] } } } }, title: { zlevel: 0, text: [ '{value|' + (total / 1000 > 1 ? (total / 1000).toFixed(2) + '万' : total) + '}', '{name|总数}' ].join('\n'), top: 'center', left: '27%', textAlign: 'center', textStyle: { rich: { value: { color: '#303133', fontSize: 40, fontWeight: 'bold', lineHeight: 50 }, name: { color: '#303133', fontSize: 18, lineHeight: 28 } } } }, color: [ '#37D4CF', '#F76560', '#4080FF', '#F99057', '#B5E241', '#E13EDB', '#8D4EDA', '#A9AEB8' ], tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } } }, series: [ { type: 'pie', center: ['28%', '50%'], radius: ['45%', '60%'], avoidLabelOverlap: false, hoverAnimation: false, // 取消掉环形图鼠标移上去时自动放大 itemStyle: { // 图形外文字上下显示 normal: { label: { show: false }, labelLine: { show: false } } }, label: { show: false, position: 'center' }, emphasis: { label: { show: false, fontSize: '20' } }, labelLine: { show: false }, data: this.dataList } ] } option && myChart.setOption(option) }
