vue echarts Error in nextTick: “TypeError: Cannot read property ‘getAttribute‘ of undefined“
写在前面:导致 Error in nextTick: “TypeError: Cannot read property ‘getAttribute’ of undefined”报错原因就是因为获取不到页面的元素,导致这种报错的因素很多种,我这里至少记录下在vue子组件件中使用echart获取不到页面元素,使用vue插槽解决。1. 报错 Error in nextTick: "TypeError:
写在前面:导致 Error in nextTick: “TypeError: Cannot read property ‘getAttribute’ of undefined”
报错原因就是因为获取不到页面的元素
,导致这种报错的因素很多种,我这里至少记录下在vue子组件件中使用echart获取不到页面元素,使用vue插槽解决。
1. 报错 Error in nextTick: "TypeError: Cannot read property 'getAttribute' of undefined"
2. 分析原因(报错的背景)在vue页面中,页面使用到了echarts,但是出现了上面的报错,简单分析原因。是获取不到 myChart
这个元素。但是页面已经写了。于是我们就考虑页面是否渲染完成,在在mounted
里面和 this.$nextTick
写了,但是依然获取不到 ref
。最后发现:我写在了子组件中,是获取不到echarts。
<box :title="title" :style="styleObj">
<div ref="myChart" id="myChart" :style="{width: '5.17rem', height: '0.85rem'}"></div>
</box>
mounted() {
this.$nextTick(function() {
let echarts = this.$refs.myChart;
console.log(echarts )
})
}
依然报错直接是undefined
3. 解决办法 使用vue插槽,插槽的含义就是在组件中可以引用一切页面。
3.1 在子组件中 添加 <slot name="content"></slot>
命名name为content
Box.vue 页面
<template>
<div id="box-page">
<div class="box" :style="styleObj">
<div :class="title!='社区管理工作综合排行榜'?'title':'log-title'">{{title}}</div>
<slot name="content"></slot>
</div>
</div>
</template>
3.2 在daily-task.vue页面中引用Box ,在 <template #content>
中添加echarts。#content
为子组件的具名
<template>
<div id="daily-task">
<box :title="title" :style="styleObj">
<template #content>
<div ref="myChart" id="myChart" :style="{width: '5.17rem', height: '0.85rem'}"></div>
</template>
</box>
</div>
</template>
import Box from "@/components/Box";
export default {
name: "daily-task",
//import引入的组件需要注入到对象中才能使用
components: {
Box
},
}
最后打印测试就可以拿到页面的echarts,然后就可以进行echats渲染了。
更多推荐
所有评论(0)