Vue 3 中动态获取高宽

发布时间 2024-01-12 10:18:44作者: 蓝色精灵jah

1.监听父组件的 宽高

2.将监听到的高度赋给 你需要设置的对象

  :: 引入监听 并实现 如何得到动态宽度 (此时的 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节点对象
    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; 
这样获取的值是有单位的。