我正在制作一个有n x n
个正方形组件的电路板组件.我想根据棋盘的宽度来设定正方形的大小,大概是board.offsetWidth / boardCols
.
我如何才能将正方形的大小或父母的宽度传递给子元素?
父级宽度设置为0.5vh,因此在组件安装之前,我不能知道电路板的宽度(以像素为单位),但props 在安装之前通过.
以下是父组件:
<template>
<div ref="board" class="board">
<square-component :square-size="squareSize" v-for="square in rows*cols"></square-component>
</div>
</template>
<script setup>
//I'm working on Nuxt, no imports needed
const board = ref()
const props = defineProps({
cols: {type: Number, default: 10},
rows: {type: Number, default: 10},
})
const squareSize = computed(() => {
//here, board value is undefined
const squareSize = board.value.offsetWidth / props.rows
return squareSize
})
</script>
<style>
.board {
width: .5vh
}
</style>
这是子元素:
<template>
<div :style=[sizeStyle, myOtherComputedStyles]></div>
</template>
<script setup>
const props = defineProps({
squareSize: {type: Number, required: true}
})
const sizeStyle = computed(() => {
return {
width: `${props.squareSize}px`
height: `${props.squareSize}px`
}
})
</script>
有没有办法实现这一点?