During VueCONF US 2019, Chris Fritz (Vue.js Core Team Emeriti) pointed out
The use of the .native
modifier can lead to broken components in Vue 2, especially when the root element of the base input changes unexpectedly. This modifier, considered an anti-pattern by Chris, will be removed in Vue 3. To address this issue, he recommended avoiding the .native
modifier and utilizing the $listeners
property instead to explicitly define parent care for element listeners.
Working with Vue 2
Utilizing $listeners
:
To resolve this issue in Vue 2, Chris proposed using a fully transparent wrapper approach. By leveraging the $listeners
property that contains all component listeners, developers can ensure seamless functionality without relying on the problematic .native
modifier.
{
focus: function (event) { /* ... */ }
input: function (value) { /* ... */ },
}
Simply adding v-on="$listeners"
to the test
component achieves this:
Test.vue (child component)
<template>
<div v-on="$listeners">
click here
</div>
</template>
The <test>
component, now a fully transparent wrapper, functions like a regular <div>
element, ensuring all listeners work without relying on .native
.
Check out the Demo:
...
Using $emit
method:
Another approach suggested by Chris is using the $emit
method to listen to child component events in the parent component. By emitting custom events from the child component and listening to them in the parent, a seamless communication channel is established.
Test.vue (child component)
<test @click="$emit('my-event')"></test>
In the parent component, listening to the custom event is as simple as:
App.vue
<test @my-event="testFunction"></test>
By adopting this approach, event handling in Vue 2 takes a more organized and structured form.
Check out the Demo:
...
Transitioning to Vue 3
Embracing v-bind="$attrs"
:
With the upcoming Vue 3 release, Chris highlighted the convenience it brings, particularly in creating simpler transparent wrappers using v-bind="$attrs"
. This attribute allows for effortless handling of child component attributes and events, making development more streamlined.
In Vue 3, the root element automatically listens to all child events, eliminating the need for manual adjustments in most cases.
Explore Demo #1:
...
For scenarios requiring attribute and event delegation to child elements like <input />
, v-bind="$attrs"
proves to be a handy tool.
Experience Demo #2:
...