{nextT"/> {nextT">
刚好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页面加载完成后怎么获取宽度、高度的详细内容。更多信息请关注PHP中文网其他相关文章!