TIL that you need to v-bind $attrs in Vue
POSTED ON:
TAGS: vue
In Vue (Vue3?), you have to bind $attrs to multi-root components.
// THE PARENT FILE
<form>
<label>Select a category</label>
<BaseInput
v-model="event.title"
label="Title"
type="text"
/>
</form>
// THE MULTI-ROOT COMPONENT -- called BaseInput.vue
<input
v-bind="$attrs"
:value="modelValue"
:placeholder="label"
@input="$emit('update:modelValue', $event.target.value)"
class="field"
>
So now, you pass your HTML attributes from the parent->multi-root component, and the component can know what to do with it.
Assigning the $attrs to the input
In Vue, whenever you pass down attributes, classes and styles from a parent to a child like we are doing with the type in our BaseInput component, Vue will attempt to automatically figure out where inside your template these attributes should be injected.
In components with a single wrapping element, also known as single root components, this behavior is very straightforward. Vue will simply inject all the attributes, classes and styles into the root element.
In multi-root components, such as our BaseInput, Vue can’t figure out without our help which one of the nodes, or fragments, it should inject the attributes to — so Vue simply gives up and issues a warning.
In the case of our BaseInput component, we want to be able to inject attributes directly into the input, so we have to manually bind the $attrs object to it. Let’s go ahead and do that now by adding v-bind="$attrs” to our input element.
REFERENCE:
Via https://www.vuemastery.com/courses/vue3-forms/base-input
Related TILs
Tagged: vue