微信小程序开发使用echarts报错Cannot read property ‘getAttribute‘ of undefined

微信小程序开发使用echarts报错Cannot read property ‘getAttribute‘ of undefined_第1张图片

如图,我在小程序圈中的区域渲染echarts图标报错了,报错提示Cannot read property 'getAttribute' of undefined 

微信小程序开发使用echarts报错Cannot read property ‘getAttribute‘ of undefined_第2张图片

 

微信小程序开发使用echarts报错Cannot read property ‘getAttribute‘ of undefined_第3张图片

 这里的canvas ,width ,height,dpr获取为 undefined

分析问题:

  1. 初始化图表时传递错误的参数

    onShow 生命周期方法中调用 this.initChart() 方法时,并没有传递 canvaswidthheightdpr 参数。这可能导致 canvasundefined。要解决这个问题,确保在调用 initChart() 方法时正确传递这些参数。

  2. 未正确设置图表初始化回调

    data 中定义的 ecec1 对象中,onInit 属性的值被设为空字符串 '',这意味着初始化回调函数没有被正确设置。在 onShow 生命周期方法中,虽然调用了 this.initChart() 方法,但并未把初始化函数返回的图表对象与 ecec1 对象中的 onInit 属性绑定起来。因此,图表对象无法正确传递给小程序组件。为了解决这个问题,需要修改 onShow 方法中的代码如下:

/**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      ec:{
        onInit:this.initChart.bind(this)
      },
      ec1:{
        onInit:this.initChart1.bind(this)
      }
    })
  },

解决问题了,使用 bind 方法将 this.initChartthis.initChart1 函数与 ecec1 对象中的 onInit 属性绑定起来,并确保在 initChartinitChart1 函数中可以访问到 Page 实例的 data

微信小程序开发使用echarts报错Cannot read property ‘getAttribute‘ of undefined_第4张图片

现在可以正常显示并且不报错了 

你可能感兴趣的:(微信小程序,echarts,小程序)