Vue?3?中動態(tài)獲取高寬的思路詳解
更新時間:2023年10月14日 09:46:18 作者:牧碼士
這篇文章主要介紹了Vue3中動態(tài)獲取高寬,實現思路大概是將監(jiān)聽到的高度賦給你需要設置的對象,本文通過實例代碼給大家介紹的非常詳細,需要的朋友一起看看吧
應用場景: 一般用于父組件動態(tài)變換寬高,子組件需要同步修改寬高
實現簡介 : Vue3 寫法
思路:
1.監(jiān)聽父組件的 寬高
2.將監(jiān)聽到的高度賦給 你需要設置的對象
:: 引入監(jiān)聽 并實現 如何得到動態(tài)寬度 (此時的 div2 會與 divDom 寬度會保持一致)
<template> <div ref="divDom"></div> //你可以手動或者換成可拖拉伸縮的盒子 <div ref= "div2" :style="{'width':leftShowWith.with}"></div> </template> 第一種 獲取方式 <script setup> import {useResizeObserver} from "@vueuse/core"; const divDom =ref(); const leftShowWith = reactive({ with:'500px' }); useResizeObserver(divDom , (entries) => { const entry = entries[0] const { width, height } = entry.contentRect console.log(`width: ${width}, height: ${height}`) console.log(`${width}px`) leftShowWith.with = `${width}px`; }) </script>
一些補充的知識
1、了解 如何獲取組件的對象
<template> <div ref="divDom"></div> </template> 第一種 獲取方式 <script setup> import { ref, getCurrentInstance } from 'vue'; const divDom = ref(null); onMounted(()=>{ console.log('獲取dom元素',divDom) }) // 獲取頁面的實例對象 const pageInstance = getCurrentInstance(); // 獲取dom節(jié)點對象 const tagDomObj = pageInstance.refs.divDom; </script> 第一種 獲取方式 <script setup> const divDom =ref(); </script>
2、了解 如何獲取元素中的寬高
<div ref="init"></div> 寫在 頁面 方法 部分 這里的 offsetHeight 是返回元素的寬度(包括元素寬度、內邊距和邊框,不包括外邊距) let height= this.$refs.init.$el.offsetHeight; let height= divDom.VALUE.$el.offsetHeight; // 在Vue3 中的寫法 這里的offsetHeight可以替換,用來獲取其他的屬性 offsetWidth //返回元素的寬度(包括元素寬度、內邊距和邊框,不包括外邊距) offsetHeight //返回元素的高度(包括元素高度、內邊距和邊框,不包括外邊距) clientWidth //返回元素的寬度(包括元素寬度、內邊距,不包括邊框和外邊距) clientHeight //返回元素的高度(包括元素高度、內邊距,不包括邊框和外邊距) style.width //返回元素的寬度(包括元素寬度,不包括內邊距、邊框和外邊距) style.height //返回元素的高度(包括元素高度,不包括內邊距、邊框和外邊距) scrollWidth //返回元素的寬度(包括元素寬度、內邊距和溢出尺寸,不包括邊框和外邊距),無溢出的情況,與clientWidth相同 scrollHeigh //返回元素的高度(包括元素高度、內邊距和溢出尺寸,不包括邊框和外邊距),無溢出的情況,與clientHeight相同 除此之外,還可以獲取帶有單位的數值 let height = window.getComputedStyle(this.$refs.init).height; 這樣獲取的值是有單位的。
到此這篇關于Vue 3 中動態(tài)獲取高寬的文章就介紹到這了,更多相關vue3動態(tài)獲取高寬內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!