写在前面:
如本文描述有错误,希望读到这篇文章的您能够提出批评指正。 联系方式:172310978@qq.com
参考文章:
- https://www.yisu.com/zixun/798253.html
vue3页面加载完成后获取宽度、高度
刚好H5项目有用到这个需求,页面加载完成后获取当前页面高度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <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版本的也可以用语法糖来处理,直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <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
未使用nextTike
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <!-- \* 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <!-- \* 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>
|
最新资讯
相关推荐
相关标签
vue组件
vue插件
vuejs
vuedraggable
vue框架
vue.component
vue2.0
vuerouter
vue-video-player
MongoVUE
vue-cli3.x
vue.set
.vue
vue2.6
vue.js2.0
vue-devtools
vue-pdf
vue-resource
vue.js组件
vue-test-utils