Application scenario : Generally used to dynamically change the width and height of the parent component, and the child component needs to modify the width and height synchronously
Implementation introduction: Vue3 writing method
Idea:
1. Monitor the width and height of the parent component
2. Assign the monitored height to the object you need to set
:: Introduce monitoring and implement how to get the dynamic width (at this time, the width of div2 will be consistent with the width of 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>
some additional knowledge
1. Understand how to obtain the object of the component
<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. Understand how to get the width and height of an element
<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;
这样获取的值是有单位的。