欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

VUE2.0+Element-UI+Echarts封装的组件实例

程序员文章站 2022-06-16 22:30:08
本文用vue2.0+elementui的panel组件和table组件+echarts的柱状图和折线图实现对结果的展示,实现了表格和图之间的切换和图和表之间的转置。 -h...

本文用vue2.0+elementui的panel组件和table组件+echarts的柱状图和折线图实现对结果的展示,实现了表格和图之间的切换和图和表之间的转置。

-html

<div class="resultdiv">
  <div id="panels">
   <el-collapse>
    <el-collapse-item v-for="item in indicators">
    <template slot="title">
     <span class='resulticon'>
      {{item.indicatorname}} 
      <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="el-icon-upload2" :class="item.indicatorname" download="somedata.xls" @click="return exportexcel(item.indicatorname)" 
       data-command="show" title="保存为表"></a>
      <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="glyphicon glyphicon-repeat" aria-hidden="true" @click="convert" data-command="show" title="图表切换"></a>
      <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="glyphicon glyphicon-transfer" aria-hidden="true" @click="transpose" data-command="show" title="行列转置"></a>
     </span>
    </template>
    <template>
     <div v-show="tableandmap==3?true:tableandmap==1?true:false" :id="item.indicatorname"></div>
    </template>
    <template v-if="tableandmap==3?true:tableandmap==2?true:false">
     <el-table :data="item.tabledata" max-height="300" stripe border fix style="width: 100%">
      <el-table-column v-for="(column,index) in item.columns" :prop="column" :fixed="index==0" :label="column" min-width="150"></el-table-column>
     </el-table>
    </template>
    </el-collapse-item>
   </el-collapse>
  </div> 
 </div>

js,panel组件的代码

var panelsvue = new vue({
 el : "#panels",
 props : ["initdata","indicators","mapoptions"],
 data : {
  roworcolumn : false, //行列转换
  tableormap : true, //表和图切换
  tableandmap : 3, //表和图同时显示
  mapinitoption : {
    title: {
     text: ''
    },
    tooltip : {
     trigger: 'axis'
    },
    toolbox: {
     show : true,
     feature : {
      mark : {show: true},
      dataview : {show: true, readonly: false},
      magictype : {show: true, type: ['line', 'bar']},
      restore : {show: true},
      saveasimage : {show: true}
     }
    },
    calculable : true,
    xaxis : [
     {
      type : 'category',
      boundarygap : false
     }
    ],
    yaxis : [
     {
      type : 'value',
      axislabel : {
       formatter: '{value}'
      }
     }
    ]
   } //echarts 初始化参数
 },
 methods:{
  table : function(ev){
   if(this.roworcolumn){
    this.indicators=this.listtorowobject(this.initdata);
    this.mapoptions= this.listtocolumnmap(this.initdata);
    this.roworcolumn=false;
   }else{
    this.indicators=this.listtocolumnobject(this.initdata);
    this.mapoptions= this.listtorowmap(this.initdata);
    this.roworcolumn=true;
   }
   for(var i=0;i<this.mapoptions.length;i++){
    var indicatorname= this.mapoptions[i].title.text;
    var dom = document.getelementbyid([indicatorname])
    var heigth = $(dom).siblings('div').height()*1.5;
    var width = $(dom).siblings('div').width();
    $(dom).css({
     height:heigth,
     width:width
    });
    var mychart= echarts.init(document.getelementbyid([indicatorname]),'macarons');
    mychart.setoption(this.mapoptions[i]);
   }
   ev.stoppropagation();
  },
  listtorowobject :function (listandlist){
   var indicatornames=[];
   var tabledatas=[];
   var columns = [];
   var options = [];
   listandlist = listandlist.indicatorresult;
   for(var i=0;i<listandlist.indicatornames.length;i++){
    var objects=[];
    var column =[];
    var indicatorname = listandlist.indicatornames[i];
    for(var yindex in listandlist[indicatorname]){
     var obj = {};
     obj[indicatorname]=listandlist.colkeys[yindex];
     for(var xindex in listandlist[indicatorname][yindex]){
      obj[listandlist.rowkeys[xindex]]=listandlist[indicatorname][yindex][xindex];
     }
     objects.push(obj);
    }
    indicatornames.push(indicatorname);
    column.push(indicatorname);
    column=column.concat(listandlist.rowkeys);
    var indicator={};
    indicator[indicatorname]=objects;
    columns.push(column);
    tabledatas.push(indicator);
   }
   for(var j = 0; j<indicatornames.length;j++){
    var indicatorobj = {};
    indicatorobj["tabledata"]=tabledatas[j][indicatornames[j]];
    indicatorobj["columns"] = columns[j];
    indicatorobj["indicatorname"] = indicatornames[j];
    options.push(indicatorobj);
   }
   return options;
   },
   listtocolumnobject :function (listandlist) {
    var options = [];
    var columns = [];
    var indicatornames = [];
    var indicatormap = {};
    listandlist = listandlist.indicatorresult;
    for (var i = 0; i < listandlist.indicatornames.length; i++) {
     var column = [];
     var objs = [];
     var indicatorname = listandlist.indicatornames[i];
     indicatornames.push(indicatorname);
     column.push(indicatorname);
     column = column.concat(listandlist.colkeys);
     columns.push(column);
     var indicatordata = [];
     indicatordata.push(listandlist.rowkeys);
     indicatordata = indicatordata.concat(listandlist[indicatorname]);
     for (var k = 0; k < indicatordata[0].length; k++) {
      var arow = {};
      for (var j = 0; j < indicatordata.length; j++) {
       arow[column[j]] = indicatordata[j][k];
      }
      objs.push(arow);
     }
     indicatormap[indicatorname] = objs;
    }
    for (var j = 0; j < indicatornames.length; j++) {
     var indicatorobj = {};
     indicatorobj["tabledata"] = indicatormap[indicatornames[j]];
     indicatorobj["columns"] = columns[j];
     indicatorobj["indicatorname"] = indicatornames[j];
     options.push(indicatorobj);
    }
    return options;
   },
   listtocolumnmap: function(listandlist){
     listandlist = listandlist.indicatorresult;
     var options=[];
     for(var j = 0;j<listandlist.indicatornames.length;j++){
      var sigleoption ={};
      sigleoption=json.parse(json.stringify(this.mapinitoption));//实现深复制
      sigleoption.xaxis[0]["data"]=listandlist.rowkeys;
      var indicatorname = listandlist.indicatornames[j];
      sigleoption["title"]["text"]=indicatorname;
      var series =[];
      for(var k=0;k<listandlist[indicatorname].length;k++){
       var sigleserie={type:'line'};
       sigleserie["name"] = listandlist.colkeys[k];
       sigleserie["data"] = listandlist[indicatorname][k];
       series.push(sigleserie);
      }
      sigleoption["series"]=series;
      options.push(sigleoption);
     };
     return options;
   },
   listtorowmap: function(listandlist){
     listandlist = listandlist.indicatorresult;
     var options=[];
     for(var j = 0;j<listandlist.indicatornames.length;j++){
      var sigleoption ={};
      sigleoption=json.parse(json.stringify(this.mapinitoption));//实现深复制
      sigleoption.xaxis[0]["data"]=listandlist.colkeys;
      var indicatorname = listandlist.indicatornames[j];
      sigleoption["title"]["text"]=indicatorname;
      var series =[];
      for(var k=0;k<listandlist.rowkeys.length;k++){
       var sigleserie={type:'line'};
       var x= [];
       for(var z = 0;z<listandlist.colkeys.length;z++){
        x.push(listandlist[indicatorname][z][k]);
       }
       sigleserie["name"] = listandlist.rowkeys[k];
       sigleserie["data"] = x;
       series.push(sigleserie);
      }
      sigleoption["series"]=series;
      options.push(sigleoption);
     };
     return options;
   },
   map : function(ev){
    if(this.tableandmap==1){
     this.tableandmap=2;
    }else if(this.tableandmap==2){
     this.tableandmap=3;
    }else{
     this.tableandmap=1;
    }
    ev.stoppropagation();
   },
   exportexcel : function(indicatorname,my){
    debugger;
    console.log(indicatorname);
    var listandlist = json.parse(json.stringify(this.initdata.indicatorresult));
    var rowtd = listandlist.rowkeys;
    var excelldata=[];
    rowtd.splice(0,0,indicatorname);
    excelldata.push(rowtd);
    for(var i = 0;i<listandlist[indicatorname].length;i++){
     var rowtr = listandlist[indicatorname][i];
     rowtr.splice(0,0,listandlist.colkeys[i]);
     excelldata.push(rowtr);
    }
    return excellentexport.excelbydata($("."+indicatorname)[0], excelldata, 'sheet', 'download' + new date().gettime() + '.xls');
   }
 },
 watch : {
  initdata : function(newvalue){
   this.indicators=this.listtorowobject(newvalue);
  }
 },
 mounted : function(){
 }
});
vue.set(panelsvue,'initdata',listandlist);

在使用上述组件过程中,发现当转置和表格切换之后里面全部都有变化,虽然可以做到单个panel组件自己实现转置和切换,但是发现如果数据太多会导致页面卡死,为了性能优化所以后来考虑采用多vue对象的形式(虽然我的思路是如果改变数据之后,vue将重新渲染html,导致页面卡死,但是后来仔细查资料之后,发现vue当数据改变之后会复用原来相同的html。但是由于时间的原因,也没试。大家可以考虑一下)

采用多vue对象的形式之后的页面

html

<div class="resultdiv"></div>

js,panel组件

var panelsvuearr = [];
var responsedata;
function createhtml(respdata){
 var indicatorresult = respdata.indicatorresult; 
 var indicators = [];
 for(var j=0;j<indicatorresult.indicatornames.length;j++){
  var indicator = {};
  indicator["indicatorname"]=indicatorresult.indicatornames[j];
  indicator["indicatorunit"]=indicatorresult.indicatorunits[j];
  indicator["rowkeys"]=indicatorresult.rowkeys;
  indicator["colkeys"]=indicatorresult.colkeys;
  indicator["indicatordata"]=indicatorresult[indicatorresult.indicatornames[j]];
  indicators.push(indicator);
 }
 for(var i =0;i<indicators.length;i++){
  var el = $("<div></div>");
  $(".resultdiv").append(el[0]); 
  var vueobj = new vue({
   el : el[0],
   template : '<div id="panels"><el-collapse><el-collapse-item>'+
   '<template slot="title"><span class="resulticon">{{item.indicatorname}}({{item.indicatorunit}}) <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="el-icon-upload2" :class="item.indicatorname" download="somedata.xls" @click="exportexcel" data-command="show" title="保存为表"></a>'+
   '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="glyphicon glyphicon-repeat" aria-hidden="true" @click="convert" data-command="show" title="图表切换"></a><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="glyphicon glyphicon-transfer" aria-hidden="true" @click="transpose" data-command="show" title="行列转置"></a>'+
  '</span></template><template><div v-show="!tableandmap" :id="item.indicatorname"></div></template><template v-if="tableandmap"><el-table :data="item.tabledata" max-height="300" stripe border fix fit style="width: 100%">'+
   '<el-table-column v-for="(column,index) in item.columns" :prop="column" :fixed="index==0" :label="column" :min-width="column.length<8?118:column.length>16?250:column.length*15"></el-table-column></el-table></template></el-collapse-item></el-collapse></div>',
   props : ['item','mapoption'],
   data : {
    indicator : indicators[i],
    roworcolumn : false, // 行列转换
    tableormap : true, // 表和图切换
    tableandmap : true, // 表和图同时显示
    indexid : i,
    mapinitoption : {
     title : {
      text : '',
      show : false
     },
     tooltip : {
      trigger : 'item',
      formatter: ''
     },
     legend : {
      data : [],
      right : 90, // 不要遮住右边的按钮
      left : 85,
      padding : 10
     },
     toolbox : {
      show : true,
      feature : {
       mark : {
        show : true
       },
       magictype : {
        show : true,
        type : ['line', 'bar']
       },
       restore : {
        show : true
       },
       saveasimage : {
        show : true
       }
      }
     },
     grid : {
      y : '',
      y2 : '',
      containlabel : true
     },
     calculable : true,
     xaxis : [{
       type : 'category',
       boundarygap : false,
       axislabel : {
        interval : 0
       // rotate : 45
       }
      }
     ],
     yaxis : [{
       type : 'value',
       axislabel : {
        formatter : yaxisformatter
       }
      }
     ]
    } // echarts 初始化参数
   },
   methods : {
    transpose : function (ev) {
     if (this.roworcolumn) {
      this.item = this.listtorowobject(this.indicator);
      this.mapoption = this.listtorowmap(this.indicator);
      this.roworcolumn = false;
     } else {
      this.item = this.listtocolumnobject(this.indicator);
      this.mapoption = this.listtocolumnmap(this.indicator);
      this.roworcolumn = true;
     }
      var indicatorname = this.mapoption.title.text;
      var mychart = echarts.init(document.getelementbyid([indicatorname]),rmp_theme);
      var grid = computergrid(this.mapoption);
      mychart.resize({
       width : grid.chartwidth+"px",
       height : grid.chartheight+"px"
      });
      mychart.setoption(this.mapoption);
     ev.stoppropagation();
    },
    listtocolumnobject : function (listandlist) {
     var x_y = column.text+"\\"+row.text;
     var itemtable ={};
     var columnr = [];
     var tabledata=[];
     for (var yindex in listandlist.indicatordata) {
      var obj = {};
      obj[x_y] = listandlist.colkeys[yindex];
      for (var xindex in listandlist.indicatordata[yindex]) {
       obj[listandlist.rowkeys[xindex]] =cellsdeal(listandlist.indicatordata[yindex][xindex],listandlist.indicatorunit);
      }
      tabledata.push(obj);
      }
     columnr.push(x_y);
     columnr = columnr.concat(listandlist.rowkeys);
     itemtable["indicatorname"]=listandlist.indicatorname;
     itemtable["tabledata"] = tabledata;
     itemtable["columns"]=columnr;
     itemtable["indicatorunit"]=listandlist.indicatorunit;
     return itemtable;
    },
    listtorowobject : function (listandlist) {
     var itemtable ={};
     var indicatormap = {};
     var indicatordata=[];
     var y_x = row.text+"\\"+column.text;
     var columnr = [];
     var tabledata = [];
     columnr.push(y_x);
     columnr = columnr.concat(listandlist.colkeys);
     indicatordata.push(listandlist.rowkeys);
     indicatordata = indicatordata.concat(listandlist.indicatordata);
     for (var k = 0; k < indicatordata[0].length; k++) {
      var arow = {};
      for (var j = 0; j < indicatordata.length; j++) {
       if(j==0){
        arow[columnr[j]] = indicatordata[j][k];
       }else{
        arow[columnr[j]] = cellsdeal(indicatordata[j][k],listandlist.indicatorunit);
       }
      }
      tabledata.push(arow);
      }
     itemtable["indicatorname"]=listandlist.indicatorname;
     itemtable["tabledata"] = tabledata;
     itemtable["columns"]=columnr;
     itemtable["indicatorunit"]=listandlist.indicatorunit;
     return itemtable;
    },
    listtocolumnmap : function (listandlist) {
     // var echartoption = echarts.getinstancebydom(document.getelementbyid(listandlist.indicatorname)).getoption();
     // var maptype = echarts.getinstancebydom(document.getelementbyid(listandlist.indicatorname)).getoption().series[0].type;
     var options = [];
      var sigleoption = {};
      sigleoption = this.mapinitoption; // 实现深复制
      var rowkeys = json.parse(json.stringify(listandlist.rowkeys));
      rowkeys.pop();
      sigleoption.xaxis[0]["data"] = rowkeys;
      var indicatorname = listandlist.indicatorname;
      sigleoption["title"]["text"] = indicatorname;
      var series = [];
      for (var k = 0; k < listandlist.indicatordata.length - 1; k++) {
       var sigleserie = {
        type : 'line',
        barmaxwidth : 40,
        barminheight : 15
       };
       sigleserie["name"] = listandlist.colkeys[k];
       var rows = json.parse(json.stringify(listandlist.indicatordata[k]))
       rows.pop();
       sigleserie["data"] = rows;
       series.push(sigleserie);
      }
      sigleoption["series"] = series;
      var legenddata = json.parse(json.stringify(listandlist.colkeys));
      legenddata.pop();
      sigleoption.legend.data = legenddata;
      var unithandle=listandlist.indicatorunit;
      sigleoption.tooltip.formatter=function (params,ticket,callback) {
       var myunit =unithandle;
       var html = '<span style="display:inline-block;margin-right:5px;"'+
       '>行:'+params.seriesname +'</span><br>';
       html+='<span style="display:inline-block;margin-right:5px;'+
       '">列:'+params.name +'</span><br>';
       var showvalue = params.value;
       if (typeof (showvalue) == "undefined") {
        showvalue = "nodata";
       } else {
        // 图悬浮框 千分位+万 +单位
        if (!isnan(showvalue)) {
         if (showvalue > 10000) {
          showvalue = tothousands((showvalue / 10000).tofixed(1)) + $.i18n.get('chart.wan')+ myunit;
         }else{
          if(unithandle=='%'){
           showvalue=parsefloat(showvalue)*100;
           showvalue = showvalue.tofixed(1) + myunit;
          }else{
           showvalue = showvalue.tofixed(1) + myunit;
          }
         }
        }
       }
       html+='<span style="display:inline-block;margin-right:5px;'+
       '">值:'+showvalue +'</span>';
       return html;
      };
     return sigleoption;
    },
    listtorowmap : function (listandlist) {
     /* var maptype;
     if(typeof(this.mapoptions)=='undefined'){
      maptype='line';
     }else{
      maptype = echarts.getinstancebydom(document.getelementbyid(listandlist.indicatornames[0])).getoption().series[0].type;
     }*/
     var options = [];
      var sigleoption = {};
      sigleoption = this.mapinitoption; // 实现深复制
      var colkeys = json.parse(json.stringify(listandlist.colkeys));
      colkeys.pop();
      sigleoption.xaxis[0]["data"] = colkeys;
      var indicatorname = listandlist.indicatorname;
      sigleoption["title"]["text"] = indicatorname;
      var series = [];
      for (var k = 0; k < listandlist.rowkeys.length - 1; k++) { // 图ttl指标去掉
       var sigleserie = {
        type : 'line',
        barmaxwidth : 40,
        barminheight : 15
       };
       var x = [];
       for (var z = 0; z < listandlist.colkeys.length - 1; z++) {
        x.push(listandlist.indicatordata[z][k]);
       }
       sigleserie["name"] = listandlist.rowkeys[k];
       sigleserie["data"] = x;
       series.push(sigleserie);
      }
      sigleoption["series"] = series;
      var legenddata = json.parse(json.stringify(listandlist.rowkeys));
      legenddata.pop();
      sigleoption.legend.data = legenddata;
      var unithandle=listandlist.indicatorunit;
      sigleoption.tooltip.formatter=function (params,ticket,callback) {
       var myunit =unithandle;
       var color = params.color;
       var html = '<span style="display:inline-block;margin-right:5px;"'
       + '">行:'+params.seriesname +'</span><br>';
       html+='<span style="display:inline-block;margin-right:5px;"'
       + '">列:'+params.name +'</span><br>';
       var showvalue = params.value;
       if (typeof (showvalue) == "undefined") {
        showvalue = "nodata";
       } else {
        // 图悬浮框 千分位+万 +单位
        if (!isnan(showvalue)) {
         if (showvalue > 10000) {
          showvalue = tothousands((showvalue / 10000).tofixed(1)) + $.i18n.get('chart.wan')+myunit;
         }else{
          if(unithandle=='%'){
           showvalue=parsefloat(showvalue)*100;
           showvalue = showvalue.tofixed(1) + myunit;
          }else{
           showvalue = showvalue.tofixed(1) + myunit;
          }
         }
        }
       }
       html+='<span style="display:inline-block;margin-right:5px;"'
       + '">值:'+showvalue +'</span>';
       return html;
      };
     return sigleoption;
    },
    convert : function (ev) {
     if (this.tableandmap) {
      this.tableandmap = false;
     } else {
      this.tableandmap = true;
     }
     var indicatorname = this.mapoption.title.text;
     var mychart = echarts.init(document.getelementbyid([indicatorname]),rmp_theme);
     var grid = computergrid(this.mapoption);
     mychart.resize({
      width : grid.chartwidth+"px",
      height : grid.chartheight+"px"
     });
     mychart.setoption(this.mapoption);
     ev.stoppropagation();
    },
    exportexcel : function (ev) {
     var listandlist = json.parse(json.stringify(this.indicator));
     var rowtd = listandlist.rowkeys;
     var excelldata = [];
     rowtd.splice(0, 0, listandlist.indicatorname+'('+listandlist.indicatorunit+')');
     excelldata.push(rowtd);
     for (var i = 0; i < listandlist.indicatordata.length; i++) {
      for(var j=0;j<listandlist.indicatordata[i].length;j++){
       listandlist.indicatordata[i][j]=cellsdeal(listandlist.indicatordata[i][j],listandlist.indicatorunit);
      }
      var rowtr = listandlist.indicatordata[i];
      rowtr.splice(0, 0, listandlist.colkeys[i]);
      excelldata.push(rowtr);
     }
     excellentexport.excelbydata($("." + listandlist.indicatorname)[0], excelldata, 'sheet', 'download' + new date().gettime() + '.xls');
     return ev.stoppropagation();
    }
   },
   watch : {
    indicator : function (newvalue) {
    }
   },
   mounted : function () {
   // this.item= this.listtorowobject(this.indicator);
   },
   beforemount : function(){
    this.item= this.listtorowobject(this.indicator);
    this.mapoption = this.listtorowmap(this.indicator);
   }
  })
  panelsvuearr.push(vueobj);
 } 
}
//格式化y轴数字显示
var yaxisformatter = function(value, index) {
 var text = value;
 if (!isnan(value)) {
  if (value > 10000) {
   // 千分位 + 万
   text = tothousands((value / 10000).tofixed(1)) + $.i18n.get('chart.wan');
  }
 }
 if (value.formatter) {
  text = value.formatter.replace("{value}", text);
 }
 return text;
}
//格式化tooltip
var tooltipformatter = function (params,ticket,callback) {
 console.log(params);
 var color = params.color;
 var html = '<span style="display:inline-block;margin-right:5px;' + 'border-radius:10px;width:9px;height:9px;background-color:'
 + color + '">行:'+params.seriesname +'</span>';
 html+='<span style="display:inline-block;margin-right:5px;' + 'border-radius:10px;width:9px;height:9px;background-color:'
 + color + '">列:'+params.name +'</span>';
 var showvalue = params.value;
 if (typeof (showvalue) == "undefined") {
  showvalue = "nodata";
 } else {
  // 图悬浮框 千分位+万 +单位
  if (!isnan(showvalue)) {
   if (showvalue > 10000||showvalue<-10000) {
    showvalue = tothousands((showvalue / 10000).tofixed(1)) + $.i18n.get('chart.wan');
   }else{
    showvalue=parsefloat(showvalue)*100;
    showvalue = showvalue.tofixed(1) + unithandle();
   }
  }
 }
 html+='<span style="display:inline-block;margin-right:5px;' + 'border-radius:10px;width:9px;height:9px;background-color:'
 + color + '">值:'+showvalue +'</span>';
 console.log(html);
 return html;
}
// 数字格式处理 1,000,000
function tothousands(num) {
 if (typeof (num) == 'undefined') {
  num = ""
 }
 num = num + '', result = '';
 if (num.indexof('%') > -1) {
  return num;
 }
 var s = "";
 if (num.indexof('.') > -1) {
  s = num.substring(num.indexof('.'), num.length);
  num = num.substring(0, num.indexof('.'));
 }
 var n = false;
 if (num.indexof('-') > -1) {
  num = num.substring(1);
  n = true;
 }
 while (num.length > 3) {
  result = ',' + num.slice(-3) + result;
  num = num.slice(0, num.length - 3);
 }
 if (num != undefined) {
  result = num + result;
 }
 if (n) {
  result = "-" + result;
 }
 if(s=='.0'){
  return result;
 }
 return result + s;
}
// 千分位与单位处理
function cellsdeal(num,unit) {
 if (typeof (num) == 'undefined') {
  num = "";
 }
 if(num===''){
  return num;
 }
 num = num + '', result = '';
 if (unit=='%') {
  num=parsefloat(num)*100;
  num = num.tofixed(1) + '';
  if(num.indexof(".")!=-1){
   return num.substring(0,num.indexof(".")+2)+"%";
  }else{
   return num+"%";
  }
 }
 var s = "";
 if (num.indexof('.') > -1) {
  num=parsefloat(num).tofixed(1);
  s = num.substring(num.indexof('.'), num.length); //小数位
  num = num.substring(0, num.indexof('.')); //整数位
 }
 var n = false;
 if (num.indexof('-') > -1) {
  num = num.substring(1);
  n = true;
 }
 while (num.length > 3) {
  result = ',' + num.slice(-3) + result;
  num = num.slice(0, num.length - 3);
 }
 if (num != undefined) {
  result = num + result;
 }
 if (n) {
  result = "-" + result;
 }
 if(unit.indexof("/")!=-1){
  s=s.substring(0,2);
 }else{
  s="";
 }
 return result + s;
}
/*动态计算echarts的grid属性 */
function computergrid(options){
 // 图宽度 默认
 var chartwidth = 810;
 // 图例占宽度比
 var legendwidth = chartwidth * 0.8;
 // 图高度默认
 var chartheight = 250;
 // 图中grid离容器下边距高度默认
 var bottomheight = 25;
 // 图中grid离容器上边距高度默认
 var topheight = 40;
 // 根据x轴刻度数量 算宽度,如果超过默认 则使用计算值
 if (options.xaxis[0].data.length * 30 - chartwidth > 0) {
  chartwidth = options.xaxis[0].data.length * 30;
 }
 // x轴刻度 最长的长度值
 var maxlength = 0;
 var legendcount = 8;
 if (options.xaxis[0].data.length > legendcount) {
  options.xaxis[0].data.foreach(function(val) {
   if (maxlength < val.length) {
    maxlength = val.length;
    if (/[^\u0000-\u00ff]/.test(val)) {
     // 计算图中grid离容器下边距高度
     bottomheight = maxlength * 14;
    } else {
     // 计算图中grid离容器下边距高度
     bottomheight = maxlength * 13.5;
    }
   }
  });
 }
 var tmpwidth = 0;
 options.legend.data.foreach(function(val) {
  if (/[^\u0000-\u00ff]/.test(val)) {
   tmpwidth += val.length * 22 + 30;
  } else {
   tmpwidth += val.length * 11 + 30;
  }
 });
 var rownum = tmpwidth / legendwidth;
 // 根据图例算 图中grid离容器上边距高度
 if (rownum > 1) {
  topheight += (rownum - 1) * 23;
 }
 chartheight += bottomheight + topheight;
 options.legend['width'] = legendwidth;
 options.grid.y2 = bottomheight;
 options.grid.y = topheight;
 if(chartwidth!='810'){
  options.grid["x"]=40;
 }
 var columnandrow = ['startprovince','startarea']; //始发省份和地区默认x轴旋转45度
 if(options.xaxis[0].data[0].match('^(\\d+)\\+(\\d+)')!=null||columnandrow.indexof(column.code)!=-1||columnandrow.indexof(row.code)!=-1){
  options.xaxis[0].axislabel['rotate']=45;
 }else{
  options.xaxis[0].axislabel['rotate']=0;
 }
 return {chartheight:chartheight,chartwidth:chartwidth};
}

上述代码实现了 echart图数据的格式化,和对数据的自适应。修改为上述方式之后发现性能提高了不止一个数量级。

以上这篇vue2.0+element-ui+echarts封装的组件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。