Solution for Vue 2
You can forward all attributes and listeners (including v-model
) from parent to child like so:
<input v-bind="$attrs" v-on="$listeners" />
Here is the documentation for $attrs:
Contains parent-scope attribute bindings (except for class
and style
) that are not recognized (and extracted) as props. When a component doesn't have any declared props, this essentially contains all parent-scope bindings (except for class
and style
), and can be passed down to an inner component via v-bind=" $attrs"
- useful when creating higher-order components.
Make sure to set inheritAttrs
to false
to avoid having attributes applied to the root element (by default, all attributes are applied to the root).
Here is the documentation for $listeners:
Contains parent-scope v-on event listeners (without .native
modifiers). This can be passed down to an inner component via v-on="$listeners"
- useful when creating transparent wrapper components.
Because v-model
is just a shorthand for v-bind
+v-on
, it is forwarded as well.
Note that this technique is available since Vue 2.4.0 (July 2017), where this feature is described as "Easier creation of wrapper components".
Solution for Vue 3
Vue 3 removed the $listeners
object because the listeners are now in the $attrs
object as well. So you only need to do this:
<input v-bind="$attrs" />
Here is the documentation for $attrs
:
Contains parent-scope attribute bindings and events that are not recognized (and extracted) as component props or custom events. When a component doesn't have any declared props or custom events, this essentially contains all parent-scope bindings, and can be passed down to an inner component via v-bind="$attrs"
- useful when creating higher-order components.
If your component has a single root element (Vue 3 allows multiple roots elements), then setting inheritAttrs
to false
is still required to avoid having attributes applied to the root element.
Here is the documentation for inheritAttrs
By default, parent scope attribute bindings that are not recognized as props will "fallthrough". This means that when we have a single-root component, these bindings will be applied to the root element of the child component as normal HTML attributes. When authoring a component that wraps a target element or another component, this may not always be the desired behavior. By setting
inheritAttrs
to false
, this default behavior can be disabled. The attributes are available via the $attrs
instance property and can be explicitly bound to a non-root element using v-bind
.
Another difference with Vue 2 is that the $attrs
object now includes class
and style
.
Here is a snippet from "Disabling Attribute Inheritance":
By setting the inheritAttrs
option to false
, you can control to apply to other elements attributes to use the component's $attrs
property, which includes all attributes not included to component props
and emits
properties (e.g., class
, style
, v-on
listeners, etc.).