在vue中,使用this.$refs.myDiv.offsetHeight获取组件高度,结果却报错,是因为...

问题描述

想要获取一个元素的高度,它的高度是不固定的,每次调用接口数据后都要重新获取它的高度,根据它的高度去变更页面中另一个元素的高度。

模板文件

<search-list ref="searchListRef" :code="currentRelation ? currentRelation.value : 1" :data="tableData" @selectRow="handleSelectRow" @gotoDetail="gotoDetail" />

脚本文件

mounted () {
    
    
	this.$nextTick(() => {
    
    
        const maxHeight = this.$refs.searchListRef.clientHeight;
	    const winHeight = document.body.clientHeight
	    this.maxHeight = maxHeight > winHeight ? maxHeight : winHeight
    })	
}

代码没有按照预期的那样运行,报错了,this.$refs.searchListRef.clientHeight报错了

报错原因分析

经过一番错误分析,发现this.$refs 访问到的是searchList这个组件,并不是他的根元素,因为我是在组件上绑定的ref,如果把ref直接绑定在div上是可以获取到dom的。

   <div ref="myDiv">Hello Vue!</div>
 methods: {
    
    
   accessDOM() {
    
    
     const myDivElement = this.$refs.myDiv;
     console.log(myDivElement); // 输出 DOM 节点
   }
 }

这种情况是可以访问到dom的。

解决方案

如果要在组件上绑定ref,可以使用下面两种方案获取到dom的值。

给组件绑定id,直接用getElementById获取dom

模板文件

<search-list ref="searchListRef" id="searchList" :code="currentRelation ? currentRelation.value : 1" :data="tableData" @selectRow="handleSelectRow" @gotoDetail="gotoDetail" />

脚本文件

mounted () {
    
    
	this.$nextTick(() => {
    
    
        const maxHeight = document.getElementById('searchList').clientHeight;;
	    const winHeight = document.body.clientHeight
	    this.maxHeight = maxHeight > winHeight ? maxHeight : winHeight
    })	
}
利用子组件的ref

子组件(ChildComponent.vue)

<template>
  <div ref="componentRoot">
    <!-- 组件内容 -->
  </div>
</template>

<script>
export default {
      
      
  name: 'ChildComponent',
  methods: {
      
      
    getHeight() {
      
      
      return this.$refs.componentRoot.clientHeight;
    },
  },
};
</script>

父组件(ParentComponent.vue)

<template>
  <div>
    <child-component ref="childComponent"></child-component>
    <button @click="logHeight">Log Height</button>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
      
      
  components: {
      
      
    ChildComponent,
  },
  methods: {
      
      
    logHeight() {
      
      
      const height = this.$refs.childComponent.getHeight();
      console.log('The height of the child component is:', height, 'px');
    },
  },
};
</script>