这篇文章主要介绍了vue3页面加载完成后怎么获取宽度、高度的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇vue3页面加载完成后怎么获取宽度、高度文章都会有所收获,下面我们一起来看看吧。
刚好H5项目有用到这个需求,页面加载完成后获取当前页面高度。
<template>
<div class="wrap" :>
</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" :>
</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>
知识点:ref,nextTike
ref可以用于dom对象的获取,以及创建一个响应式的普通对象类型
nextTick是一个函数,它接受一个函数作为参数,nextTick官网定义是‘将回调推迟到下一个 DOM 更新周期之后执行’,
<!--
* 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了,
<!--
* 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>
关于“vue3页面加载完成后怎么获取宽度、高度”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“vue3页面加载完成后怎么获取宽度、高度”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.csdn.net/hzmpkpkppk/article/details/123879056