首页 前端知识 vue3获取、设置元素高度

vue3获取、设置元素高度

2024-08-24 23:08:09 前端知识 前端哥 538 764 我要收藏

前言

在web端常见的需求场景中,会经常遇到table表格需要根据页面可视区域使高度自适应的情况。 傻喵(作者本人)昨天在尝试使用vue3实现这个需求时,看了几篇网上写的回答,都不太全面,所以干脆自己写个总结吧.(第一次写,轻喷QAQ)

正文

先一起来看看页面结构

image.png

在vue2中,实现这个效果大多是在mounted生命周期中操作DOM元素,进行元素属性的获取和修改。 升级到vue3后,生命周期前都加了on,所以在onMounted这个生命周期中操作DOM。

1、首先获取页面可视区域、header组件,至于为什么在header组件外又套了一层div,是想实验另外一个东西,先卖个关子。

setup(props) {
console.log(props);
const hd = ref(null);
let allHeight = ref("");
const test = ref(null);
onMounted(() => {
//可视区域高度
allHeight.value = `${document.documentElement.clientHeight}`;
//header组件高度
let hdHeight = hd.value.$el.clientHeight;
});
return {
hd,
test,
clienHeight,
};
},
复制

const hd = ref(null)定义的名字必须与HTML中<Header ref="hd" />这里的值相同(不相同会报错)

2、接下来就是给test组件高度赋值了,傻喵本来是想直接将值赋值的

test.value.clientHeight = headerHeight;
复制

但是没有实现效果,具体原因不得而知(有知道原因的可以在评论区告诉傻喵).
所以只能用另一种方法,style动态绑定

<Test ref="test" :style="testStyle" />
let testStyle = reactive({ height: "0px", });
testStyle.height = testHeight + "px";
复制

这样终于实现了DOM元素的赋值

3、关于在header组件外多加的一层div,是因为傻喵在获取页面元素时,发现ref获取的组件和div、span等基础标签打印出的结构不同。

image.png

如上图,依次打印的分别为<div ref="top"></div>以及它内部的header组件,基础标签会直接.value打印出来,而header组件会打印出一个Proxy对象(傻喵猜测应该是跟vue3的响应式有关,有待考究)。
这同时导致了获取两者元素属性方式的不同
div属性直接可以const top = ref(null);定义,并通过top.value.clientHeight来获取它的高度。
而header组件必须hd.value.$el.clientHeight才可以.

下面贴上完整代码

<template>
<div ref="top">
<Header ref="hd" />
</div>
<Test ref="test" :style="testStyle" />
</template>
<script>
import Header from "./components/Header.vue";
import Test from "./components/Test.vue";
import { onMounted, reactive, ref } from "vue";
export default {
name: "App",
components: {
Header,
Test,
},
setup(props) {
console.log(props);
const hd = ref(null);
const top = ref(null);
const test = ref(null);
let allHeight = ref("");
let testStyle = reactive({
height: "0px",
});
onMounted(() => {
allHeight.value = `${document.documentElement.clientHeight}`;
let hdHeight = hd.value.$el.clientHeight;
let testHeight = allHeight.value - hdHeight;
testStyle.height = testHeight + "px";
console.log(top)
console.log(hd)
console.log(top.value.clientHeight)
console.log(hd.value.$el.clientHeight)
});
return {
hd,
top,
test,
testStyle,
allHeight,
};
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin: 0px;
padding: 0px;
/* margin-top: 60px; */
}
</style>
复制

结语

以上就是傻喵使用vue3来操作元素高度的总结,还有很多坑点需要去研究。 也欢迎各位大大在评论区留言,指点一下。

文章出处:vue3获取、设置元素高度 - 掘金 (juejin.cn)

转载请注明出处或者链接地址:https://www.qianduange.cn//article/16743.html
标签
评论
发布的文章

【Linux笔记】基础IO(上)

2025-03-27 13:03:40

大家推荐的文章
会员中心 联系我 留言建议 回顶部
浏览器升级提示:您的浏览器版本较低,建议您立即升级为知了极速浏览器,极速、安全、简约,上网速度更快!立即下载
复制成功!