🔊 dom类型断言是:HTMLElement
html<template>
<div class="block-area" ref="area">
<div v-for="i of 3" :key="i" class="block" ref="divs">
{{ i }}
</div>
</div>
</template>
<script setup lang='ts'>
import { ref, onMounted, reactive, toRef } from 'vue';
const area = ref<HTMLElement | null>(null);
// const arrBlock = ref<HTMLElement[]>([]);
const divs = ref<HTMLElement[]>();
onMounted(() => {
//预留:
//1.api传来block总数
//2.block 长宽高,颜色,行为 由api传递
const min = 50;
const max = 150;
divs.value?.forEach((element, index, array) => {
console.log(`Element: ${element} 索引: ${index} ary: ${array}`);
let h = Math.floor(Math.random() * (max - min + 1)) + min;
let w = Math.floor(Math.random() * (max - min + 1)) + min;
element.style.height = `${h}px`;
element.style.width = `${w}px`;
element.style.backgroundColor = `#000`;
});
})
// const divs = (el: HTMLElement) => {
// // 断言为HTMLElement类型的数组
// if (el)
// (arrBlock.value as Array<HTMLElement>).push(el);
// };
</script>
<style scoped lang='scss'>
.block-area {
position: relative;
.block {
position: absolute;
}
}
</style>
html<!-- 第一种 -->
<div :ref="(el)=> boxHanddlde(el)"></div>
<!-- 第二种 -->
<div :ref="(el)=> boxArray.push(el)"></div>
<script lang='ts'>
let boxArray = reactive<any[]>([])
const boxHanddle(e:any){
console.log(e)
}
onMounted(()=>{
console.log(boxArray)
})
</script>
本文作者:宁骑
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!