Nuxt应用中this.$refs返回undefined,无法读取div高度该如何解决?
问题原因
- 你将
ref绑定在普通HTML div元素上,而非Vue组件实例,无需通过.$el获取DOM对象,this.$refs.modelDiv本身就是对应的原生DOM元素 - 只有在
v-for循环中声明的ref才会返回数组类型,当前是单个元素绑定ref,直接取值即可,额外添加[0]会读取undefined的属性,直接触发报错 - 隐藏问题:你使用
v-if控制分支显隐,当displayMe切换为false时,v-if分支的DOM会被直接销毁,this.$refs.modelDiv会变为undefined,若后续需要复用高度建议首次拿到高度后永久缓存,或者将v-if替换为v-show保留DOM结构。如果Component1内部有异步渲染的内容(比如接口请求后渲染),还需要在Component1渲染完成后向父组件发送事件,触发父组件重新计算高度。
修正后代码
<template> <div> <div v-if="showMe"> <div ref="modelDiv"> <Component1/> </div> </div> <div v-else> <div :style="setDivHeight"> <Component2/> </div> </div> </div> </template> <script> export default { data() { return { displayMe: true, elementHeight: null, } }, computed: { showMe() { return this.displayMe }, setDivHeight() { return `height: ${this.elementHeight}px;` }, }, mounted() { this.$nextTick(function () { // 移除[0]和.$el,直接读取DOM的clientHeight属性 this.elementHeight = this.$refs.modelDiv.clientHeight }) }, } </script>
内容的提问来源于stack exchange,提问作者Maxime
相关产品推荐
相关产品推荐

