vue中this.$refs获取不到组件元素的解决办法
http://www.allyns.cn/info/162
当我们在vue开发中遇到使用this.$refs报错获取不到组件元素时。
<template>
<div class="dataQueryEventGraphDialog">
<hg-dialog :title="title" :width="950" :height="485" :visible="dialogVisible" @close="handleClose">
<div class="graph" ref="graph" style="height:calc(100vh - 50px);">
<RelationGraph ref="seeksRelationGraph" :options="graphOptions" :on-node-click="onNodeClick" :on-line-click="onLineClick"/>
</div>
</hg-dialog>
</div>
</template>
<script>
import HgDialog from '@/components/dialog';
import RelationGraph from '@/components/relationGraph'
export default {
....//
watch: {
show(val) {
this.dialogVisible = val;
if(this.dialogVisible){
this.showSeeksGraph();
}
}
},
methods: {
showSeeksGraph() {
var graph_json_data = {
rootId: 'a',
nodes: [
// node配置选项:http://relation-graph.com/#/docs/node
// node支持通过插槽slot完全自定义,示例:http://relation-graph.com/#/demo/adv-slot
{ id: 'a', text: 'A', borderColor: 'yellow' },
{ id: 'b', text: 'B', color: '#43a2f1', fontColor: 'yellow' },
{ id: 'c', text: 'C', nodeShape: 1, width: 80, height: 60 },
{ id: 'e', text: 'E', nodeShape: 0, width: 150, height: 150 }
],
lines: [
// link配置选项:http://relation-graph.com/#/docs/link
{ from: 'a', to: 'b', text: '关系1', color: '#43a2f1' },
{ from: 'a', to: 'c', text: '关系2' },
{ from: 'a', to: 'e', text: '关系3' },
{ from: 'b', to: 'e', color: '#67C23A' }
]
}
this.$refs.seeksRelationGraph.setJsonData(graph_json_data, (seeksRGGraph) => {
// Called when the relation-graph is completed
})
},
onNodeClick(nodeObject, $event) {
console.log('onNodeClick:', nodeObject)
},
onLineClick(linkObject, $event) {
console.log('onLineClick:', linkObject)
}
}
};
主要原因就是组件还没有加载完毕,然后就调用了组件内的属性,导致报错Cannot read properties of undefined (reading 'setJsonData')" 无法读取未定义的属性。
1、必须要等页面中的ref子组件加载完毕,才可以获取到
2、在mounted之前的钩子函数中获取不到,可以用this.$nextTick(()=>{})
3、组件在v-if的作用下,导致这个子组件未渲染,也是导致获取不到的因素,后续等渲染出来再用refs也是获取不到的
我这里的解决方法就是调用时加上this.$nextTick(()=>{})
show(val) {
this.dialogVisible = val;
if(this.dialogVisible){
this.$nextTick(()=>{
this.showSeeksGraph();
})
}
}
标签:
前端Vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)