最近一个项目中使用了VUE,并需要绘制图表,这就尴尬了,搜查了很多资料,发现网上使用的有:npm-c3,v-charts,sChart,D3等等多种多样,经过至少不下5中可视化组件尝试,发现最好用的还是Echarts。

主要原因:

1.有官方实例和API,资源丰富,遇到问题可快速解决

2.支持图标类型多样化,能满足项目扩展需求

3.图表操作灵活,配置项可封装,自由度高

废话少说,直接上代码吧,在这里就不说用npm引入echarts,自行百度吧,主要分享代码,这样方面大家参考,以柱图为例

VUE HTML部分:

<template>
  <div id="chart_example"> </div>
</template>
style scoped>
  #chart_example{
    width: 100%;
    height:100%;
  }
</style>

js代码部分:

import echarts from 'echarts'
import echatrsMC from '../../mEchartsUtil2MC'//这个是我Echarts的封装
import util from '../../util'//这个是请求封装,可以不用管
export default {
  data() {
    return {}
  },
  mounted() {
    let $this = this
    // let myChart = echarts.init(document.getElementById('chart_example'))
    let yData = ['我','叫','冒','菜','AND','我','L','O','V','E','I','T']
    let xData = [1314, 521, 215, 125, 111, 55,16,10,5,3,2,1]
    let idList = []
    let mURL = '填写你要发送的请求'
    util.ajax2MC('get',mURL, null, function (result) {//数据处理仅仅供参考
      if(result.data){
        yData = []
        xData = []
        for (let i = 0; i < result.data.length; i++) {
          yData.push(result.data[i].psnNm)
          xData.push(result.data[i].cost)
          idList.push(result.data[i].psnId)
        }
        let option = echatrsMC.getOneBarOption(yData,xData)//封装代码中获取option实例
//特别注意下面三行代码要写到请求中,不然会出现echarts实例化dom元素了,但是数据没有绑定上,因为请求的数据还没返回echarts就已经实例了,这样写能解决该问题
        var myChart = echarts.init(document.getElementById('chart_example'))
        myChart.clear()
        myChart.setOption(option,true)
        myChart.on('click', function (params) {//绑定点击事件
          let idx = params.dataIndex
          let id = idList[idx]
          console.log(id)
          $this.$f7.views.main.router.reloadPage('/logsts/logStsPsnWork/'+id)//界面跳转,不用管
        })
      }
    })
  },
  methods: {},
  watch: {},
  created() {

  }
}

分享下封装的代码自行参考,util.js:

mport _ from 'lodash'
import axios from 'axios'
import * as copy from 'copy-to-clipboard'
import store from './store'
import routes from './routes.js'
import base64url from 'base64-url'
import cookie from 'js-cookie'
import qs from 'qs'
export default {
/**
 * 异步请求调用
 * @param type 请求类型 post/get
 * @param method 方法名
 * @param payload 请求内容
 * @param callback 回调函数
 */
ajax2MC(type, method, payload, callback) {
  let httpUrl, httpMethod
  if(type === 'get'){
    httpMethod = 'get'
  } else {
    httpMethod = 'post'
  }
  httpUrl = env.apiBaseUrl + '/' + method
  this.log('调用参数' + payload)
  this.log('请求URL:' + httpUrl)
  window.f7.showIndicator()
  let that = this
  axios({
    method: httpMethod,
    url: httpUrl,
    timeout: 1000 * 12, // 创建axios实例,设定超时时间是12s
    data: qs.stringify(payload),
    withCredentials:true,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  })
    .then(function (response) {
      window.f7.hideIndicator()
      let returnFlag = response.data.code
      let returnInfo = response.data.message
      if (returnFlag === 0) {
        callback(response.data)
      } else if (returnFlag === 10) {
        window.f7.confirm('<p>用户登录已失效</p><p>点击确定重新登录</p>', function () {
          window.f7.loginScreen()
        })
      } else {
        window.f7.alert('<p>错误代码: ' + returnFlag + '</p><p>原因: ' + returnInfo + '</p>')
      }
    })
    .catch(function (error) {
      window.f7.hideIndicator()
      that.log(error)
      window.f7.alert('服务调用失败,请检查网络连接')
    })
}
}

 

封装的echarts.js部分mEchartsUtil2MC.js:

export default {
  getOneBarOption(yData,xData){
    let barColorList = ['#3c9bd3','#3dc0e4','#66dede','#9aeb2','#fdd65d','#fb9479','#f6658b','#d956a5','#e085ca','#e3b4f0']//柱图色值
    let barGridInfo = {   //绘图区调整
      x:80,  //左留白
      y:10,   //上留白
      x2:80,  //右留白
      y2:10   //下留白
    }
    //横向单柱图option
    return{
      tooltip : {
        trigger: 'item'  //悬浮提示框不显示
      },
      grid:barGridInfo,
      xAxis : [
        {
          show:false,
          type : 'value',
          boundaryGap : [0, 0],
          position: 'top'
        }
      ],
      yAxis : [
        {
          type : 'category',
          data :yData,
          axisLine:{
            show:false,
            textStyle: {
              code:function(params) {
                return barColorList[params.dataIndex]
              }
            }
          },     //坐标轴
          axisTick:[{    //坐标轴小标记
            show:false
          }],
          axisLabel:{
            textStyle:{
              fontSize:'15',
              color: '#3dc0e4'
            }
          }
        }
      ],
      series : [
        {
          name:'',
          type:'bar',
          tooltip:{show:false},
          barMinHeight:10,  //最小柱高
          barWidth: 20,  //柱宽度
          barMaxWidth:100,   //最大柱宽度
          data:xData,
          itemStyle:{
            normal:{    //柱状图颜色
              color:function(params) {
                return barColorList[params.dataIndex]
              },
              label:{
                show: true,   //显示文本
                position: 'right',  //数据值位置
                textStyle:{
                  color:function(params) {
                    return barColorList[params.dataIndex]
                  },
                  fontSize:'15'
                }
              }
            }
          }
        }
      ]
    }
  },
  getPieOption(btData){
    return{
      color:['#3c9bd3','#e085ca','#e3b4f0','#3dc0e4','#66dede','#9aeb2','#fdd65d','#fb9479','#f6658b','#d956a5'],
      series : [
        {
          name: '',
          type: 'pie',
          radius : '75%',
          center: ['50%', '50%'],
          data:btData,
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  }
}


Logo

前往低代码交流专区

更多推荐