Normally, we use this directive to bind any HTML form element with a variable to collect the input value. But often we need to bind with a form element, that is present in a different component. In this case, you have to use a v-model to custom components.
In this way, you can bind a variable with an HTML element that is inside a child component.
In the latest version of Vue i.e.
Vue 3, we have to follow different rules than we used to follow in Vue 2. In this article, I will show you how you can add the v-model to custom components in Vue 3 very easily in the best possible way.
If you are using Vue 2, you can follow our other post on how to add v-model to custom components in Vue2.
- In Vue 2, we had only one way to create a component.
- But in Vue 3, we can create a component in 3 different ways. Options API (This is old-style was available in Vue 2). Composition API. SFC (Single File Components) Script Setup.
- I will show you how you can use the v-model to custom components using all three ways. Before following this article, there are some basic requirements that you need to have.
For example, if the value in the form element changes then the value stored in the variable will also change automatically at the same time.
It will also update the value in every place that variable was used in the template so that users always see the latest value.
This process is very helpful if we have to show the changes in real-time to our users.
In Vue, the v-model directive uses this technique by default. As you know, we use v-model to bind a variable and a form element together so that if you change the value in one place it also changes in another one.