vue3页面加载完成后如何获取宽度、高度
目录
- vue3页面加载完成后获取宽度、高度
- vue3之vue3.2获取dom元素的宽高
- 未使用nextTike
- 使用ref+nextTick
- 总结
vue3页面加载完成后获取宽度、高度
刚好H5项目有用到这个需求,页面加载完成后获取当前页面高度,记录一下。^_^
<template>
<div class="wrap" :style="{height:hHeight+'px'}">
</div>
</template>
<script lang='ts'>
import { defineComponent, reactive, nextTick, onMounted, toRefs } from "vue";
export default defineComponent({
name: "Aboutus",
setup() {
let state = reactive({
hHeight: 0,//页面高度
});
onMounted(() => {
nextTick(()=>{
state.hHeight = document.documentElement.clientHeight;
console.log(document.documentElement.clientHeight)
})
})
return {
...toRefs(state)
}
},
});
</script>
用vue3.2版本的也可以用语法糖来处理,直接上代码:
<template>
<div class="wrap" :style="{height:state.hHeight+'px'}">
</div>
</template>
<script setup>
import { reactive, nextTick } from "vue"
const state = reactive({
hHeight: 0
})
nextTick(()=>{
state.hHeight = document.documentElement.clientHeight;
console.log(document.documentElement.clientHeight)
})
</script>
亲测可用,大家可以试试!

vue3之vue3.2获取dom元素的宽高
知识点:ref,nextTike
- ref可以用于dom对象的获取,以及创建一个响应式的普通对象类型
- nextTick是一个函数,它接受一个函数作为参数,nextTick官网定义是‘将回调推迟到下一个 DOM 更新周期之后执行’,
未使用nextTike
<!--
* new page
* @author: Blaine
* @since: 2022-06-30
* page_nextTike.vue
-->
<template>
<div class="container" >
<ul ref="myRef">
<li v-for="(item, index) in pepleList" :key="index">{{ item }}</li>
</ul>
<button @click="addHandle">增加</button>
</div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
let pepleList = reactive<string[]>(['蜘蛛侠', '钢铁侠', '美国队长'])
const myRef = ref<HTMLElement>();
onMounted(() => {
console.log('列表的高度是:', myRef.value?.clientHeight)
})
const addHandle = async() => {
pepleList.push('闪电侠')
// await nextTick()
console.log('列表的高度是:', myRef.value?.clientHeight)
}
</script>
<style scoped>
</style>

**注意:**这里的list并没有立即增加
问题在于我们改变list的值时,vue并不是立刻去更新dom,而是在一个事件循环最后再去更新dom,这样可以避免不必要的计算和dom操作,对提高性能非常重要。
那么我们需要在dom更新完成后,再去获取ul的高度,这时候就需要用到nextTick了,
使用ref+nextTick
<!--
* new page
* @author: Blaine
* @since: 2022-06-30
* page_nextTike.vue
-->
<template>
<div class="container" >
<ul ref="myRef">
<li v-for="(item, index) in pepleList" :key="index">{{ item }}</li>
</ul>
<button @click="addHandle">增加</button>
</div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
let pepleList = reactive<string[]>(['蜘蛛侠', '钢铁侠', '美国队长'])
const myRef = ref<HTMLElement>();
onMounted(() => {
console.log('列表的高度是:', myRef.value?.clientHeight)
})
const addHandle = async() => {
pepleList.push('闪电侠')
await nextTick()
console.log('列表的高度是:', myRef.value?.clientHeight)
}
</script>
<style scoped>
</style>

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)
