由于在项目中需要对数据进行可视化处理,也就是用图表展示,众所周知echarts是非常强大的插件。

npm install echarts -S
或者使用淘宝的镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install echarts -S

创建图表
首先需要全局引入
在main.js中

// 引入echarts
import echarts from ‘echarts’
Vue.prototype.$echarts = echarts

在Echarts.vue中

<template>
  <div>
      <div id="myChart" :style="{width: '300px', height: '300px'}"></div>
  </div>
</template>

<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted(){
    this.drawLine();
  },
  methods: {
    drawLine(){
        // 基于准备好的dom,初始化echarts实例
        let myChart = echarts.init(document.getElementById('myChart'))
        // 绘制图表
        myChart.setOption({
            title: { text: '在Vue中使用echarts' },
            tooltip: {},
            xAxis: {
                data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
            },
            yAxis: {},
            series: [{
                name: '销量',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20]
            }]
        });
    }
  }
}
</script>

<style>

</style>

这样我们就把echarts引入了,然后在浏览器中保存下看下
在这里插入图片描述
使用ECharts的时候遇到了报错:
Error in mounted hook: “TypeError: Cannot read property ‘init’ of undefined”
原因:echarts的引入方式错误:
正确的echarts引入方式:

let echarts = require(‘echarts’)

在这里插入图片描述

其实产生这个的原因是因为echarts的版本太高了,我们现在来看package.json里面的echarts的版本
在这里插入图片描述
一时半会拿不准问题原因,到处搜罗了一下,发现可能是版本问题,我下载的是最新的,于是卸载了echarts,安装了低版本
npm install echarts@4.8.0 --save或者let echarts = require(‘echarts’)

发现安装低于5的版本,这三种方式引入的都可以使用
在这里插入图片描述
现在我把本地的依赖都清除,然后在package.json里面把echarts删除,然后重新安装依赖看看
现在的版本是5.1.1
在这里插入图片描述

当使用全局引入的时候就会报错了
在这里插入图片描述
在这里插入图片描述
使用import的时候也是会报错
在这里插入图片描述
使用require就不会报错了
在这里插入图片描述
在这里插入图片描述
由于有大佬试过说在echarts5.0版本以上的使用这个写法import * as echarts from 'echarts’
是不会报错的我这边试了下
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结:如果echarts版本在5.0以下使用三种引入的方式都行,
如果echarts的版本在5.0以上,使用require的方式引入或者import * as echarts from 'echarts’

Logo

前往低代码交流专区

更多推荐