Today I Learned - Rocky Kev

TIL that you need to v-bind $attrs in Vue

POSTED ON:

TAGS:

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:

TIL How to implement two-way binding without a framework

One of the reasons we use React or Vue is because of that sweet sweet two-way binding. It's the automatic syncing of data between the model (data) and the view (UI) in both directions. Any changes made to the data will automatically update the view, and any changes made to the view will automatically update the data.

TIL Cherry-picking out of bootstrap-vue

If you are using a component library that uses ES modules like bootstrap-vue, you can cherry pick its components instead of just registering all of them globally.

TIL how Svelte is different fom Vue/React