Issue
I'm working on a board component that have n x n
number of square components. I want to set the square sizes based on the board width, somthing like board.offsetWidth / boardCols
.
How can I pass the square size, or the parents width, to the child?
The parent width is set to 0.5vh so I can't know the width of the board, in pixels, until the component is mounted, but the props are passed before mounted.
Here is the parent component:
<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>
And here is the child:
<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>
Is there a way to achieve it?
Solution
We can change squareSize
from computed
to ref(0)
and create ResizeObserver
in onMounted()
to change and watch it. At that time board.value
will be a proper DOM element:
<script setup>
import {ref, computed, onMounted} from 'vue';
import squareComponent from './square-component.vue';
const board = ref(), squareSize = ref(0);
const props = defineProps({
cols: {type: Number, default: 10},
rows: {type: Number, default: 10},
});
onMounted(() => new ResizeObserver(() => squareSize.value = board.value.offsetWidth / props.rows).observe(board.value));
</script>
Answered By - Alexander Nenashev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.