echarts在vue中的导入和入门使用以及Cannot read property ‘getAttribute‘ of null“的解决方法

echarts官网:https://echarts.apache.org/zh/index.html

先看效果图

echarts在vue中的导入和入门使用以及Cannot read property ‘getAttribute‘ of null“的解决方法_第1张图片

 

1.echart导入vue

先在项目目录终端输入下面指令安装一下echart,用cnpm装会比较快

npm install echarts --save
或者
cnpm install echarts --save

在main.js中导入echart

import echarts from 'echarts'
Vue.prototype.$echarts = echarts

2.使用

在vue中要用ref不能用document.getElementById来获取元素,否则会下面的错:Cannot read property 'getAttribute' of null"

echarts在vue中的导入和入门使用以及Cannot read property ‘getAttribute‘ of null“的解决方法_第2张图片

 解决方法:

①在vue中要用ref来获取元素然后初始化echarts,然后写好方法后在mounted中调用(详细见完整代码模板)

②注意:写好后的方法一定要在mounted中调用而不能在created中调用,因为echarts初始化一定要等这个html渲染完后才可以进行

③尤其注意一下盒子的宽高一定要给足够大,否则会出现图表不显示或者显示不全的情况,比如下面图的横坐标就是指显示了三个数据,其实有五个

echarts在vue中的导入和入门使用以及Cannot read property ‘getAttribute‘ of null“的解决方法_第3张图片

 

 

let chart= this.$refs.songsType;
const myChart = this.$echarts.init(chart)

下面是完整的代码

    mounted(){
      this.demo();
    },
      methods:{
        demo(){
          // 基于准备好的dom,初始化echarts实例
          let chart= this.$refs.songsType;
          const myChart = this.$echarts.init(chart)
          // var myChart = this.$echarts.init(document.getElementById('songsType'))
          // console.log(myChart);
          // 绘制图表
          myChart.setOption({
            title: { text: '歌曲类型数据统计' },
            tooltip: {},
            xAxis: {
              data: ["华语","欧美","日韩","BGM","纯音乐","轻音乐"]
            },
            yAxis: {},
            series: [{
              name: '数量',
              type: 'bar',
              data: [5, 20, 36, 10, 10, 20]
            }]
          });
        }
    }

你可能感兴趣的:(vue)