【Vue+Echarts】天坑 子组件中的Echarts Cannot read properties of undefined (reading ‘getAttribute‘)“

Error in nextTick: “TypeError: Cannot read properties of undefined (reading ‘getAttribute’)”

报错 Error in nextTick: “TypeError: Cannot read properties of undefined (reading ‘getAttribute’)”

Echarts无法加载

情景

子组件中存在Echarts图 父组件中点击才展开显示

原因

在子组件中默认通过:v-if隐藏元素,导致Echarts未被初始化加载出来;
大部分情况
通过钩子函数加载Echarts表格

 // ...渲染Echarts
  mounted() {
    this.initCharts();
  },

大部分情况通过此方法解决:

将初始化图表的函数放在 this.$nextTick 函数中,可以确保在 DOM 更新完毕后再执行图表的初始化,从而避免了访问 undefined 引用的错误。

mounted() {
    this.$nextTick(() => {
      this.initCharts();
    });
  },

解决方案

将 v-if 改为 v-show。v-if 仅在条件为真时渲染 DOM 元素,因此可能会导致 ECharts 初始化失败。而 v-show 始终渲染 DOM 元素,只是在条件为假时将其隐藏。
然后,在组件的 watch 选项中,通过监听v-show=”somevalue“ 的somevalue来控制我们的Echarts渲染。
部分代码:

<div v-show="somevalue" style="margin: 5px;">
    somevalue(newVal, oldVal) {
      if (newVal !== oldVal && newVal) {
        this.$nextTick(() => {
          this.initPieCharts();
        });
      }
    },
  }
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue,父组件调用组件的方法或属性,可能会出现"Cannot read properties of undefined"的错误。这通常是因为父组件在调用组件的方法或属性时,组件还未完全加载或初始化。 要解决这个问题,可以采取以下几种方法: 1. 使用v-if指令:在父组件,使用v-if指令来确保组件已经加载完毕再进行调用。例如: ```html <template> <div> <child-component v-if="isChildLoaded" ref="childComponent"></child-component> <button @click="callChildMethod">调用组件方法</button> </div> </template> <script> export default { data() { return { isChildLoaded: false }; }, mounted() { // 组件加载完毕后设置isChildLoaded为true this.isChildLoaded = true; }, methods: { callChildMethod() { // 调用组件方法前先判断组件是否已加载 if (this.isChildLoaded) { this.$refs.childComponent.childMethod(); } } } }; </script> ``` 2. 使用$nextTick方法:在父组件,使用$nextTick方法来确保组件已经渲染完毕再进行调用。例如: ```html <template> <div> <child-component ref="childComponent"></child-component> <button @click="callChildMethod">调用组件方法</button> </div> </template> <script> export default { methods: { callChildMethod() { this.$nextTick(() => { this.$refs.childComponent.childMethod(); }); } } }; </script> ``` 以上是两种常见的解决方法,根据具体情况选择适合的方式来解决父组件调用组件时出现的错误。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值