在Vue和React中使用ECharts的多種方法

前言

俗話說:「工欲善其事,必先利其器」。現現在已經有許多成熟易用的可視化解決方案,例如ECharts,AntV等等。咱們能夠把這些解決方案比做是一套套成熟的「工具」,那咱們如何將這些「工具」應用於當前最熱門的兩個前端框架中呢?前端

不慌,如今咱們就以ECharts爲例,來嘗試「工具」的各類用法。vue

Vue中運用ECharts

首先咱們要把ECharts下載下來:react

npm install echarts --save

全局引用

全局引用的好處就是咱們一次性把ECharts引入項目後,就能夠在任何一個組件中使用ECharts了。npm

首先在項目的main.js中引入ECharts,而後將其綁定在vue的原型上面:前端框架

import echarts from 'echarts'

Vue.prototype.$echarts = echarts

接下來咱們就能夠在本身想用ECharts的組件中引用了:echarts

<template>
  <div>
    <div id="myChart"></div>
  </div>
</template>

<script>
export default{
  name: 'chart',
  data () {
    return {
      chart: null,
      options: {}
    }
  },
  mounted () {
    this.initOptions()
    this.initCharts()
  },
  methods: {
    initOptions () {
      this.options = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [820, 932, 901, 934, 1290, 1330, 1320],
          type: 'line'
        }]
      }
    },
    initCharts () {
      this.chart = this.$echarts.init(document.getElementById('myChart'))
      this.chart.setOption(this.options)
    }
  }
}
</script>

<style scoped>
  #myChart{
    width: 400px;
    height: 400px;
  }
</style>

看看效果:框架

按需引用

全局引用是把Echarts完整的引入,這樣作的缺點就是會額外的引入不少其餘沒有用的配置文件,可能會致使項目體積過大。若是所以資源加載的時間過長的話,也會影響人們的體驗,畢竟人們都喜歡快和更快。less

針對上述問題,咱們能夠採用按需引入的方式。若是有不少頁面都須要用到
Echarts的話,那咱們就在main.js中引入:工具

let echarts = require('echarts/lib/echarts')

require('echarts/lib/chart/line')

require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')

Vue.prototype.$echarts = echarts

若是隻是在偶爾幾個頁面引用,也能夠單獨在.vue引入:測試

<script>
let echarts = require('echarts/lib/echarts')

require('echarts/lib/chart/line')

require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')

</script>

而後再改一下Echarts的配置項:

this.options = {
    title: {
      text: "測試表格"
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [820, 932, 901, 934, 1290, 1330, 1320],
      type: 'line'
    }]
}

ref獲取DOM

咱們能夠發現,上面的例子都是用getElementById()來獲取渲染圖表的div,一樣咱們也能夠用ref來對真實的DOM進行操做。咱們把代碼做如下修改:

<template>
  <div>
    <div id="myChart" ref="myChart"></div>
  </div>
</template>
initCharts () {
  // this.chart = this.$echarts.init(document.getElementById('myChart'))
  this.chart = this.$echarts.init(this.$refs.myChart)
  this.chart.setOption(this.options)
}

最終獲得的效果是同樣的

React中運用ECharts

在React中運用ECharts的方式和Vue有不少類似之處,只是在寫法上有些許不一樣

所有引入

chart.jsx

import React, { Component } from 'react';
import echarts from 'echarts'
import './chart.less';

export class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data:[820, 932, 901, 934, 1290, 1330, 1320]
        }
    }

    componentDidMount(){
        this.initCharts();
    }
    //初始化
    initCharts = () => {
        let myChart = echarts.init(document.getElementById('myChart'));
        let option = {
            title: {
                text: "測試表格-react"
              },
              tooltip: {
                trigger: 'axis'
              },
              xAxis: {
                type: 'category',
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
              },
              yAxis: {
                type: 'value'
              },
              series: [{
                data: this.state.data,
                type: 'line'
              }]
        };
        myChart.setOption(option);
        window.addEventListener("resize", function () {
            myChart.resize();
        });
    }

    render(){
        return (
            <div className="chart">
                <div id="myChart"></div>
            </div>
        )
    }
}

chart.less

.chart{
    display: flex;
    flex: 1;
    #myChart{
        width: 400px;
        height: 400px;
    }
}

效果

按需引入

在React中,若是把ECharts整個引入,也會面臨項目包體積過大所形成的負面影響。固然也能夠在React中按需引入ECharts,方法和Vue相似

import echarts = 'echarts/lib/echarts'

import 'echarts/lib/chart/line'

import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'

在React-Hooks中使用

在之前沒有Hook的時候,咱們都是在class裏面寫代碼,就如上述的方法同樣。可是如今既然Hook這個好東西出來了,哪有不用的道理?

import React, { useEffect, useRef } from 'react';
import echarts from 'echarts';

function MyChart () {
    const chartRef = useRef()
    let myChart = null
    const options = {
        title: {
            text: "測試表格-react-hook"
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line'
        }]
    }

    function renderChart() {
        const chart = echarts.getInstanceByDom(chartRef.current)
        if (chart) {
            myChart = chart
        } else {
            myChart = echarts.init(chartRef.current)
        }
        myChart.setOption(options)
    }

    useEffect(() => {
        renderChart()
        return () => {
            myChart && myChart.dispose()
        }
    })

    return (
        <>
            <div style={{width: "400px", height: "400px"}} ref={chartRef} />
        </>
    )
}

export default MyChart

看看效果

既然咱們已經在Hook中成功引用了Echarts,那麼爲什麼不把代碼抽離出來,使之能讓咱們進行復用呢?咱們能夠根據實際狀況把一些數據做爲參數進行傳遞:

useChart.js

import React, { useEffect } from 'react';
import echarts from 'echarts';

function useChart (chartRef, options) {

    let myChart = null;

    function renderChart() {
        const chart = echarts.getInstanceByDom(chartRef.current)
        if (chart) {
            myChart = chart
        } else {
            myChart = echarts.init(chartRef.current)
        }
        myChart.setOption(options)
    };

    useEffect(() => {
        renderChart()
    }, [options])

    useEffect(() => {
        return () => {
            myChart && myChart.dispose()
        }
    }, [])

    return
}

export default useChart

接下來引用咱們剛抽離好的Hook:

import React, { useRef } from 'react'
import useChart from './useChart'

function Chart () {
  const chartRef = useRef(null)
  const options = {
    title: {
        text: "測試表格 react-hook 抽離"
    },
    tooltip: {
        trigger: 'axis'
    },
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        type: 'line'
    }]
  }
  useChart (chartRef, options)

  return (
    <>
        <div style={{width: "400px", height: "400px"}} ref={chartRef} />
    </>
  )
}

export default Chart

最後

本文主要總結了ECharts做爲數據可視化的高效工具在當今熱門的幾種前端框架中的基本用法。相信對於這方面接觸較少的小夥伴來講應該仍是會有必定的幫助滴~

文章如有不足或有更好建議,歡迎提出,你們一塊兒討論~

相關文章
相關標籤/搜索