父组件调用子组件this.$refs.xxx报Cannot read properties of undefined (reading ‘xxx‘)“[已解决]

Error in v-on handler: "TypeError: Cannot read properties of undefined (reading ‘xxx‘)“

父组件在通过this.$refs获取子组件的属性和方法

子组件:
  <!-- 饼图报表 -->
    <chartReport v-if="isShow == 1" ref="detailChart" />
  
  //调用:  
  getTypeSearch(e) {
    
    
      this.isShow = e
      if (e == 1) {
    
    
      //inventoryChart()为子组件的方法
          this.$refs.detailChart.inventoryChart()
    }    

报错:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler: “TypeError: Cannot read properties of undefined (reading ‘inventoryChart’)”

解决

  getTypeSearch(e) {
    
    
      this.isShow = e
      if (e == 1) {
    
    
        this.$nextTick(() => {
    
    
          console.log(this.$refs.detailChart.inventoryChart(), 'this.$refs.detailChart')
          this.$refs.detailChart.inventoryChart()
        })
  }  

原因:

vue还没进行加载完子组件的方法的时候就开始进行执行子组件方法就会报这个错误,解决的办法很简单,只要在让方法在vue加载完子组件之后再进行执行

this.$nextTick()将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。

猜你喜欢

转载自blog.csdn.net/Maxueyingying/article/details/130502695