Using v-model + $attrs on Vue Components

Filip Stępień
2 min readApr 4, 2019

--

The v-model directive is used to create a two-way data binding in Vue by doing two things: It binds a value attribute to an element, and listens for input event to be emitted. Vue docs show how v-model can be used on both inputs and custom components:

Using v-model can be helpful for a custom BaseInput component or as in the example below a component with a set of input fields. You might want to group input fields that will be used if multiple forms throughout your site, for example user or address fields. Initially I used props to pass the user object and emitting out an input event. Adding v-model to the parent reduces the code in UserForm.vue but still requires the emit to be written out on each input element. To shorten this code further v-model can be used on each input element with $attrs.value.key.

Just a quick check in dev tools to make sure everything is still reactive:

Here is a codesandbox of the example:

Further Reading

--

--