Using v-model + $attrs on Vue Components
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
- Chris Fritz — If you like $attrs you may like Vue 3, here are slides from VueConfUS showing the future of v-model / $attrs - What I’m most exited for in Vue 3.0
- Maintaining a single source of truth while handling form data with Vuex — uses the same form in this article to demonstrate a pattern to handle Vuex state and diffs while form handling.
- VueDose — Adaptive components using v-bind and v-on