关于前端:在Vue和React中使用ECharts的多种方法

前言

俗话说:“工欲善其事,必先利其器”。现如今曾经有许多成熟易用的可视化解决方案,例如ECharts,AntV等等。咱们能够把这些解决方案比作是一套套成熟的“工具”,那咱们如何将这些“工具”利用于以后最热门的两个前端框架中呢?

不慌,当初咱们就以ECharts为例,来尝试“工具”的各种用法。

Vue中使用ECharts

首先咱们要把ECharts下载下来:

npm install echarts --save

全局援用

全局援用的益处就是咱们一次性把ECharts引入我的项目后,就能够在任何一个组件中应用ECharts了。

首先在我的项目的main.js中引入ECharts,而后将其绑定在vue的原型下面:

import echarts from 'echarts'

Vue.prototype.$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残缺的引入,这样做的毛病就是会额定的引入很多其余没有用的配置文件,可能会导致我的项目体积过大。如果因而资源加载的工夫过长的话,也会影响人们的体验,毕竟人们都喜爱快和更快。

针对上述问题,咱们能够采纳按需引入的形式。如果有很多页面都须要用到
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作为数据可视化的高效工具在当今热门的几种前端框架中的根本用法。置信对于这方面接触较少的小伙伴来说应该还是会有肯定的帮忙滴~

文章若有有余或有更好倡议,欢送提出,大家一起探讨~

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理