#剛好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>
##vue3之vue3.2取得dom元素的寬高
知識點:ref,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>
<!-- * 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中文網其他相關文章!