Coming from a React background, I am used to being able to easily alter children components before they render. However, after spending hours reading the VueJS documentation and searching forums, I have not been able to find a straightforward way to do this in VueJS.
Here is an example of what I am trying to achieve:
<FormField :fieldName="myFieldName">
<NumericInput
:value="2"
></NumericInput>
</FormField>
I want the FormField
component to pass the fieldName
to the NumericInput
:
export default class FormField {
@Prop()
private fieldName!: string;
}
<template>
<div class="form-field">
<slot :fieldName="fieldName"></slot>
</div>
</template>
Unfortunately, this approach does not seem to work as intended. The NumericInput
component does not receive the name. According to the documentation, I should follow this method instead:
<FormField :fieldName="myFieldName">
<template v-slot="slotProps">
<NumericInput
:fieldName="slotProps.fieldName"
:value="2"
></NumericInput>
</template>
</FormField>
While this solution does work, I am not satisfied with having the grand-parent component responsible for passing props between FormField
and
NumericInput</code. I wish for the <code>FormField
itself to determine how and whether it passes down the fieldName
prop to the NumericInput
. Additionally, I don't understand why I need to specify the binding of fieldName
on both the NumericInput
component and the slot
for it to function correctly.
In React, handling such situations is much simpler with the ability to iterate through children using React.children
and modify or add props effortlessly.