ECharts在Vue和React中的各种使用方法
#myChart{width:400px;身高:400像素;}前言俗话说:工欲善其事,必先利其器。现在有很多成熟好用的可视化方案,比如ECharts、AntV等。我们可以将这些方案比作一套成熟的“工具”,那么我们如何将这些“工具”应用到目前最流行的两种前端框架中呢?别着急,下面我们就以ECharts为例,尝试一下“工具”的各种用法。要在Vue中使用ECharts,首先要下载ECharts:npminstallecharts--saveglobalreference全局引用的好处是我们在项目中一次性引入ECharts后,可以在任何组件中使用ECharts。先在项目的main.js中引入ECharts,然后绑定到vue的prototype上:importechartsfrom'echarts'Vue.prototype.$echarts=echarts然后在我们要使用ECharts的组件中引用它添加:
#myChart{width:400px;身高:400像素;}看效果:按需引用全局引用是为了全面引入Echarts,这样做的缺点是会额外引入很多其他无用的配置文件,可能会导致项目体积过大。如果加载时间过长,也会影响人们的体验。毕竟,人们喜欢越来越快。针对以上问题,我们可以采用按需导入的方式。如果有很多页面需要使用Echarts,那么我们在main.js中引入:letecharts=require('echarts/lib/echarts')require('echarts/lib/chart/line')require('echarts/lib/component/tooltip')require('echarts/lib/component/title')Vue.prototype.$echarts=echarts如果只是偶尔在几个页面引用,也可以单独在.vue中引入:然后更改Echarts的配置项:this.options={title:{text:"TestForm"},tooltip:{trigger:'axis'},xAxis:{type:'category',data:['Mon','Tue','Wed','Thu','Fri','Sat','Sun']},yAxis:{type:'value'},series:[{数据:[820,932,901,934,1290,1330,1320],type:'line'}]}ref获取DOM我们可以发现上面的例子使用了getElementById()来获取渲染图表的div,我们也可以使用引用真实DOM到操作。我们修改代码如下: 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.jsximportReact,{Component}from'react';从'echarts'导入'导入echarts。/chart.less';exportclassAppextendsComponent{constructor(props){super(props);this.state={data:[820,932,901,934,1290,1330,1320]}}componentDidMount(){this.initCharts();}//初始化initCharts=()=>{letmyChart=echarts.init(document.getElementById('myChart'));让option={title:{text:"TestForm-react"},tooltip:{trigger:'axis'},xAxis:{type:'category',data:['Mon','Tue','Wed','Thu','Fri','Sat','Sun']},yAxis:{类型:'价值'},系列:[{数据:this.state.data,类型:'线'}]};myChart.setOption(选项);window.addEventListener("resize",function(){myChart.resize();});}render(){return(