I'm relatively new to Vue JS and it is my first frontend framework. I used Vue 3 without deep prior knowledge of CSS & HTML.
I have coded a few components for my job but one thing I realised is that I tend to put width & height as the props almost all the time. (Then maybe use a computed property for the child component's style)
Example below:
<template>
<child-component :style="childStyle" class="child">
...
</child-component>
<svg>
<rect :width=`${getChildWidth(width)}` :height=`${getChildHeight(height)}` viewBox=`0 0 ${getChildWidth(width)} ${getChildHeight(height)}`/>
<svg/>
</template>
<script setup lang="ts">
import {computed, toRefs} from 'vue';
const props = defineProps({
width: {
type: Number as PropType<number>,
required: true,
},
height: {
type: Number as PropType<number>,
required: true,
},
})
const { width, height } = toRefs(props)
function getChildWidth(width: number) { ... }
function getChildHeight(height: number) { ... }
const childStyle = computed<StyleValue>(() => ({
width : `${getChildWidth(width)}px`,
height : `${getChildHeight(height)}px`,
}))
</script>
<style scoped>
.child {
...
}
</style>
My question is whether there are any best practices associated with managing Vue component sizes more dynamically and also what's the best way (with a simple example) to use CSS to dynamically control child-component's size. I'm afraid that using Javascript to dynamically control component sizes all the time may reduce code reusability and/or introduce a lot of code. Pls enlighten me. Thank you.
Edit 1 : Add SVG into the question
Thank you user entio for your answer. Sorry I forgot to add SVG because that's when I think that I'm forced to explicitly use pixel sizes propped down from the parent. How should I do the same with components containing SVG elements?