在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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sherry Tian

打赏1元鼓励作者

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值