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


Posted in Javascript onMarch 02, 2018

本文用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封装的组件实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
Jquery 获取表单text,areatext,radio,checkbox,select值的代码
Nov 12 Javascript
js获取指定日期周数以及星期几的小例子
Jun 27 Javascript
AngularJS实现全选反选功能
Dec 08 Javascript
AngularJs Injecting Services Into Controllers详解
Sep 02 Javascript
jQuery Ajax File Upload实例源码
Dec 12 Javascript
Node.js+Express+MySql实现用户登录注册功能
Jul 10 Javascript
使用vue官方提供的模板vue-cli搭建一个helloWorld案例分析
Jan 16 Javascript
js判断输入框不能为空格或null值的实现方法
Mar 02 Javascript
js传递数组参数到后台controller的方法
Mar 29 Javascript
用npm安装vue和vue-cli,并使用webpack创建项目的方法
Sep 28 Javascript
详解如何探测小程序返回到webview页面
May 14 Javascript
Vue使用axios出现options请求方法
May 30 Javascript
vue中添加mp3音频文件的方法
Mar 02 #Javascript
JS中利用FileReader实现上传图片前本地预览功能
Mar 02 #Javascript
select标签设置默认选中的选项方法
Mar 02 #Javascript
原生JavaScript实现todolist功能
Mar 02 #Javascript
js判断输入框不能为空格或null值的实现方法
Mar 02 #Javascript
vue判断input输入内容全是空格的方法
Mar 02 #Javascript
Spring Boot/VUE中路由传递参数的实现代码
Mar 02 #Javascript
You might like
在Yii2特定页面如何禁用调试工具栏Debug Toolbar详解
2017/08/07 PHP
php利用云片网实现短信验证码功能的示例代码
2017/11/18 PHP
javascript 限制输入和粘贴(IE,firefox测试通过)
2008/11/14 Javascript
Javascript select控件操作大全(新增、修改、删除、选中、清空、判断存在等)
2008/12/19 Javascript
28个JS验证函数收集
2010/03/02 Javascript
js选取多个或单个元素的实现代码(用class)
2012/08/22 Javascript
jQuery 过滤方法filter()选择具有特殊属性的元素
2014/06/15 Javascript
js实现页面刷新滚动条位置不变
2016/11/27 Javascript
javascript实现一个网页加载进度loading
2017/01/04 Javascript
微信小程序多列选择器range-key使用详解
2020/03/30 Javascript
快速解决vue-cli在ie9+中无效的问题
2018/09/04 Javascript
Vue监听事件实现计数点击依次增加的方法
2018/09/26 Javascript
Element输入框带历史查询记录的实现示例
2019/01/15 Javascript
vue防止花括号{{}}闪烁v-text和v-html、v-cloak用法示例
2019/03/13 Javascript
vue element中axios下载文件(后端Python)
2019/05/10 Javascript
微信小程序的开发范式BeautyWe.js入门详解
2019/07/10 Javascript
vue.js实现数据库的JSON数据输出渲染到html页面功能示例
2019/08/03 Javascript
nodejs各种姿势断点调试的方法
2020/06/18 NodeJs
[47:26]完美世界DOTA2联赛 LBZS vs Forest 第二场 11.07
2020/11/09 DOTA
python和pyqt实现360的CLable控件
2014/02/21 Python
python OpenCV学习笔记实现二维直方图
2018/02/08 Python
Python各类图像库的图片读写方式总结(推荐)
2018/02/23 Python
python ddt数据驱动最简实例代码
2019/02/22 Python
详解python播放音频的三种方法
2019/09/23 Python
解决python -m pip install --upgrade pip 升级不成功问题
2020/03/05 Python
马来西亚最热门的在线时尚商店:FashionValet
2018/11/11 全球购物
总经理岗位职责
2013/11/09 职场文书
献爱心倡议书
2014/04/14 职场文书
志愿者爱心公益活动策划方案
2014/09/15 职场文书
群众路线党员个人整改措施
2014/10/27 职场文书
夫妻吵架保证书
2015/05/08 职场文书
女方离婚起诉书
2015/05/18 职场文书
汤姆叔叔的小屋读书笔记
2015/06/30 职场文书
2017年寒假社区服务活动总结
2016/04/06 职场文书
求职信如何撰写?
2019/05/22 职场文书
vue组件冲突之引用另一个组件出现组件不显示的问题
2022/04/13 Vue.js