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

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

先看效果图

 

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"

 解决方法:

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

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

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

 

 

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]
            }]
          });
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值