vue3 script setup 组合式api 如何计算插槽元素的宽高
在 Vue3 的组合式 API 中,可以使用 useRef 来获取组件内部的 DOM 元素,并计算其宽高。
例如,在 setup 函数中,可以定义一个 ref 对象来引用插槽元素:
import { ref } from 'vue'
export default {
setup(props, { slots }) {
const slotRef = ref(null)
// ...
}
}
然后,在模板中使用 slot 元素并设置 ref 属性:
<template>
<div>
<slot ref="slotRef"></slot>
</div>
</template>
最后,在 onMounted 生命周期钩子中,可以获取插槽元素的宽高:
import { ref, onMounted } from 'vue'
export default {
setup(props, { slots }) {
const slotRef = ref(null)
const slotWidth = ref(0)
const slotHeight = ref(0)
onMounted(() => {
const slotEl = slotRef.value
if (slotEl) {
slotWidth.value = slotEl.offsetWidth
slotHeight.value = slotEl.offsetHeight
}
})
// ...
}
}
这样,就可以通过 slotWidth 和 slotHeight 来获取插槽元素的宽高了。
原文地址: https://www.cveoy.top/t/topic/brB3 著作权归作者所有。请勿转载和采集!