vue中this.$refs获取不到组件元素的解决办法

发布时间 2023-06-16 12:48:49作者: sunny123456

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();
      })
    }
  }