前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >echarts常用功能封装|抽象为mixin

echarts常用功能封装|抽象为mixin

原创
作者头像
大前端分享
修改2020-10-26 11:59:47
7760
修改2020-10-26 11:59:47
举报
文章被收录于专栏:大前端分享

目前已解锁以下功能:

  • 初始化echarts(initChart)
  • 获取echarts参数配置(getOption)
  • 生成echarts图表(setOption)
  • 监听resize事件触发echarts图表更新
  • 加载中loading
代码语言:txt
复制
// charts.js
import echarts from 'echarts'

export default {
  computed: {
    // 初始化echarts
    getChart () {
      return this.$echarts.init(this.$refs.echart)
    }
  },
  watch: {
    chartData: {
      handler (val) {
        val && this.initChart()
      }
    }
  },
  mounted () {
    this.getChart.showLoading()
    window.addEventListener('resize', this.chartResize)
    // 移除resize事件
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('resize', this.chartResize)
    })
  },
  methods: {
    initChart () {
      this.getChart.setOption(this.getOption())
      this.getChart.hideLoading()
    },
    chartResize () {
      this.getChart.resize()
    }
  }
}

example:

代码语言:txt
复制
<template>
  <div>
    <div ref="echart" style="height: 600px"></div>
  </div>
</template>

<script>
import Charts from '@/components/Charts.js'

export default {
   // 混入Charts
  mixins: [Charts],
  data () {
    return {
        chartData: []
    }
  },
  mounted () {
    // 模拟ajax请求
    setTimeout(() => {
      this.chartData = [0, 1, 2, 3]
    }, 2000)
  },
  methods: {
    getOption () {
      // 配置options
      return {
        xAxis: {
          type: "category",
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        // 代码块...
      }
    }
  }
}
</script>

ps:详情请查看examples

希望对大家有帮助哈~

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 目前已解锁以下功能:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档