因为页面中要用echarts图表的地方比较多,所以封装了组件,方便复用,如图:我需要这样一个饼图,并且接下来在很多次地方要用到。直接复制官网的代码,再改改数据,需要用的时候直接拿来用。但是接下来出现了一个问题:如果我在同一个页面多次使用这个组件,图表将不能正常显示。分析了一下, echarts通过id获取对象
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 基于准备好的dom,初始化echarts实例var myChart = echarts.init(document.getElementById('main'));当封装为组件使用的时候,id固定,同一个页面多次出现相同id,所以不能正常显示。所以想出来以下解决方案:所以想出来以下解决方案:所以想出来以下解决方案:举个栗子,如果我需要在一个页面中使用该组件两次,在组件的data中,另外赋一个变量,暂且定为type。在父组件的data中,第一个图标的数据pieData1中添加一个type:1,第二个添加一个type:2
pieData1:{
type: 1,
title: '失败次数',
list:[

{value:335, name:'502 Bad Gateway'},

{value:310, name:'404 Not Found'},

{value:234, name:'无法连接服务器'},

{value:135, name:'请求超时'},

{value:1548, name:'Trace LOSS'},
],
pieStyle: {

width: '400px',

height: '400px',

float: 'right'
}
},

pieData2:{
type: 2,
title: '失败次数',
list:[

{value:335, name:'502 Bad Gateway'},

{value:310, name:'404 Not Found'},

{value:234, name:'无法连接服务器'},

{value:135, name:'请求超时'},

{value:1548, name:'Trace LOSS'},
],
pieStyle: {

width: '400px',

height: '400px',

float: 'right'
}
}
pieData1:{
type: 1,
title: '失败次数',
list:[

{value:335, name:'502 Bad Gateway'},

{value:310, name:'404 Not Found'},

{value:234, name:'无法连接服务器'},

{value:135, name:'请求超时'},

{value:1548, name:'Trace LOSS'},
],
pieStyle: {

width: '400px',

height: '400px',

float: 'right'
}
},

pieData2:{
type: 2,
title: '失败次数',
list:[

{value:335, name:'502 Bad Gateway'},

{value:310, name:'404 Not Found'},

{value:234, name:'无法连接服务器'},

{value:135, name:'请求超时'},

{value:1548, name:'Trace LOSS'},
],
pieStyle: {

width: '400px',

height: '400px',

float: 'right'
}
}接下来改需要在同一个vue页面中用两次的子组件:html:html:


js:js:
var myPie
if(this.pieData.type==1){
myPie = echarts.init(document.getElementById("demo1"));
}else if(this.pieData.type==2){
myPie = echarts.init(document.getElementById("demo2"));
}
var myPie
if(this.pieData.type==1){
myPie = echarts.init(document.getElementById("demo1"));
}else if(this.pieData.type==2){
myPie = echarts.init(document.getElementById("demo2"));
}好了,问题解决了,效果图如下:如果想到其它方法再补充。补充知识:vue中,封装的Echart组件被同一个页面多次调用,数据被覆盖问题解决办法。补充知识:补充知识:vue中,封装的Echart组件被同一个页面多次调用,数据被覆盖问题解决办法。大概率是echarts init有问题,是不是用class或id选择器选择元素来init了错误版本:错误版本:正确版本:正确版本:以上这篇解决vue一个页面中复用同一个echarts组件的问题就是小编分享给大家的全部内容了,希望能给大家一个参考。