vue图表之echarts的图表封装的应用实践

2021-11-22  本文已影响0人  卖手机的程序猿


ECharts是啥!!


一个基于 JavaScript 的开源可视化图表库


在项目中引入 Apache ECharts


你可以使用如下命令通过 npm 安装 ECharts

获取npm的方式,本地安装node就行了,如何获取node,去node官网下载安装包,傻瓜式安装就好了

引入 ECharts


import * as echarts from 'echarts';

如果是在vue工程里使用,在main.js里,添加到vue实里面

在main.js里加入如下代码

Vue.prototype.$echarts = echarts   

在组件里通过:this.$echarts就可以调用

在工程里新建Echarts.vue文件


在templateli 加入如下代码

<template>

<div class="echarts-line"> 

  <slot name="header" class="header-box"> 

   <span> {{ title }} </span>  

</slot> 

 <div ref="myChart" id="myChart" :style="{ height: '230px' }"></div>

</div>

</template>

在script加入如下代码

export default {

name: 'EchartsLine',

data() {    return {      chart: null,    }  },

props: {    seriesData: {      type: Array,      required: true,      default: () => [],    },    extraOption: {      type: Object,      default: () => ({}),    },    xAxisOption: {      type: Object,      default: () => ({}),    },    title: {      type: String,    },  },

watch: {    seriesData: {      deep: true,      handler() {        this.drawLine()      },    },  },

mounted() {    this.drawLine()    window.addEventListener('resize', this.handleWindowResize)  },

 beforeDestroy() {    window.removeEventListener('resize', this.handleWindowResize)  },

  methods: {

mergeOptions() {      return {        // title: { text: '在Vue中使用echarts' },        tooltip: {},        dataZoom: [          // 主要是这一部分,他是折线图的缩放功能的开启          {            type: 'inside',          },        ],        grid: {          top: '8%',          left: '0%',          right: '0%',          bottom: '3%',          containLabel: true,        },        tooltip: {          trigger: 'axis',          axisPointer: {            type: 'shadow',          },        },        xAxis: this.xAxisOption,        yAxis: {          type: 'value',        },        series: this.seriesData,        ...this.extraOption,      }    },

handleWindowResize() {      if (!this.chart) return      this.chart.resize()    },

drawLine() {      console.log('this.$echarts', this.$echarts)      // 基于准备好的dom,初始化echarts实例      this.chart = this.$echarts.init(this.$refs.myChart)      let options = this.mergeOptions()      this.chart.setOption(options)    },

}

}

在style加入如下代码

<style lang="scss" scoped>

.echarts-line { 

width: 100%; 

height: 100%; 

.header {   

font-size: 14px; 

  font-weight: 400; 

  color: #000000; 

}}

</style>

组件使用方法


在要使用的组件里引入组件并在components里注册组件

import Echarts from './components/ Echarts '

components: {    Echarts  },

上一篇 下一篇

猜你喜欢

热点阅读