基于vue2写一个echarts 插件

plugin-component

分三步 1.书写 2.注册 3.使用

1. 在util文件夹下创建一个util.components.js

/**
 * @description 封装的组件函数
 **/
const components = {}
// import echarts from 'echarts'
var echarts = require('echarts')

/**
 * @description echart组件
 **/
components.echartComponent = {
  install: (Vue, options) => {
    Vue.component('echarts', {
      props: {
        width: {
          type: Number,
          default: -1
        },

        height: {
          type: Number,
          default: -1
        },

        // 控制是否执行动画
        animation: {
          type: Number,
          default: 0
        },

        // echarts基本参数
        options: {
          type: Object,
          default: () => ({})
        },

        // echarts 额外参数
        config: {
          type: Object,
          default: () => ({})
        },
      },

      data() {
        return {
          echarts_timer: null, // 定时器变量
          echarts_index: 0  // echarts动画索引
        }
      },

      // 创建视图并绑定echarts指令
      render(createElement) {
        return createElement('div', {
          attrs: {
            id: this.randomId
          },
          style: this.canvasStyle,
          directives: [
            {
              name: 'echarts'
            }
          ]
        })
      },

      mounted() {
        // 第一次渲染
        this.draw()
        // 当echarts数据还没有从后端接口获取回来之前,给一个加载动画
        this.methodShowLoading()
        // 监听echarts数据改变
        this.$watch('options', options => {
          // 数据改变,echarts内容改变
          this.draw()
          // 隐藏加载动画
          this.echartsContext.hideLoading()
        })
      },

      // 销毁定时器
      beforeDestroy() {
        clearInterval(this.echarts_timer)
        this.echarts_timer = null
      },

      computed: {
        // 生成echarts唯一ID
        randomId() {
          return (
            'echarts-' + Math.floor(Math.random() * 1000) + String(new Date().getTime()).slice(-2)
          )
        },
        // 当前echarts画布大小
        canvasStyle() {
          return {
            height: this.height === -1 ? '100%' : this.height + 'px',
            width: this.width === -1 ? '100%' : this.width + 'px'
          }
        }
      },

      methods: {
        // 此方法用以接收当前echarts实例
        recieveEchartsContext(context) {
          this.echartsContext = context
        },

        draw() {
          // 每次渲染echarts需要先清空绘画内容,清空后实例可用
          this.methodChartClear()
          // 获取echarts配置参数
          const options = this.options
          // 把echarts配置参数放入echarts实例中
          this.echartsContext.setOption(options)
          // echarts区域更新
          this.echartsContext.resize()
          this.$nextTick(() => {
            // 是否开启动画, 动画长度根据X轴
            this.animation && this.methodAnimation()
            // 是否开启事件监听
            this.config.handle && this.methodChartOnHandle(this.config.handle.event, this.config.handle.fn)
          })
          // 监听浏览器窗口改变,echarts区域更新
          window.addEventListener('resize', () => {
            this.echartsContext.resize()
          })
        },

        //图表显示提示信息
        methodShowLoading() {
          this.echartsContext.showLoading({
            text: '图表数据正在努力加载...',
            x: 'center',
            y: 'center',
            textStyle: {
              color: 'red',
              fontSize: 14
            },
            effect: 'spin'
          })
        },

        
        //ECharts图表的事件监听
        // 事件绑定,支持事件有:REFRESH,RESTORE,CLICK,HOVER,DATA_CHANGED,MAGIC_TYPE_CHANGED,DATA_VIEW_CHANGED,DATA_ZOOM,DATA_RANGE,LEGEND_SELECTED,MAP_SELECTED
        methodChartOnHandle(event, fn) {
          this.echartsContext.on(event, fn)
        },

        //解除某个事件的绑定,示例代码形如:
        methodChartUnHandle(event, fn) {
          this.echartsContext.on(event, fn)
        },

        //获取当前图表的Base64图片dataURL,imgType 图片类型,支持png|jpeg,默认为png
        methodChartImgUrl() {
          return this.echartsContext.getDataURL('png')
        },

        //获取一个当前图表的img,imgType 图片类型,支持png|jpeg,默认为png,示例代码片段:
        methodChartImgObj() {
          return this.echartsContext.getImage('jpeg')
        },

        //刷新图表,图例选择、数据区域缩放,拖拽状态均保持。
        methodChartRefresh() {
          this.echartsContext.refresh()
        },

        //还原图表,各种状态均被清除,还原为最初展现时的状态。
        methodChartRestore() {
          this.echartsContext.restore()
        },

        //清空绘画内容,清空后实例可用,因为并非释放示例的资源,释放资源我们需要dispose()
        methodChartClear() {
          this.echartsContext.clear()
        },

        //释放图表实例,释放后实例不再可用。
        methodChartDispose() {
          this.echartsContext.dispose()
        },

        methodAnimation() {
          if (this.echarts_timer) clearInterval(this.echarts_timer)
          this.echarts_timer = setInterval(() => {
            this.echartsContext.dispatchAction({
              type: 'hideTip',
              seriesIndex: 0,
              dataIndex: this.echarts_index
            })
            // 显示提示框
            this.echartsContext.dispatchAction({
              type: 'showTip',
              seriesIndex: 0,
              dataIndex: this.echarts_index
            })
            // 取消高亮指定的数据图形;
            this.echartsContext.dispatchAction({
              type: 'downplay',
              seriesIndex: 0,
              dataIndex: this.echarts_index == 0 ? this.animation - 1 : this.echarts_index - 1
            })
            this.echartsContext.dispatchAction({
              type: 'highlight',
              seriesIndex: 0,
              dataIndex: this.echarts_index
            })
            this.echarts_index++
            if (this.echarts_index > this.animation - 1) {
              this.echarts_index = 0
            }
          }, 2000)
        }
      }
    })

    Vue.directive('echarts', {
      inserted: (el, binding, vnode) => {
        // 初始化声明echarts
        const charts = echarts.init(el)
        // 把echarts实例返回给当前组件,用以存储调用
        vnode.context.recieveEchartsContext && vnode.context.recieveEchartsContext(charts)
      }
    })
  }
}

export default components

2. 在入口的文件中(比如main.js) 引入 util.components.js 文件

// 引入
import {echartComponent} from '@/util/util.components.js'
// 注册安装
Vue.use(echartComponent)

3. 在需要使用的页面调用

<echarts
  :config="echartsConfig"
  ref="echartsRef"
  :options="echartsOptions"
  :animation="echartsAnimation"
></echarts>
{
    echartsConfig: {
        // 开启事件
        handle: {
          event: 'click',
          fn: data => {
            console.log('data', data)
          }
        }
    }
    echartsOptions {
        // 这里是获取接口后合并到echarts中options的数据
        // 这边数据改变,echarts就会改变
    }
    echartsAnimation:number
    // 这个number如果是零, 则不开启动画, 开启动画, 需要告诉动画的X轴长度
}
posted @   中亿丰数字科技  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示