Create a Vue 3 Form With v-model

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

Up until this point we have been using ref for our state. But we need to create a form with multiple fields so we need to use a more complex data structure. reactive, unlike ref, does a deep comparison of the data, so we can use an array or object with it.

Then, to update our reactive data, we use the v-model property on our inputs. This keeps our data in sync with the current input value.

Instructor: [0:00] I'm going to create an updateFields variable, which is going to be a reactive version of props.craft created as a new object.

[0:12] Up till now, we've used ref rather than reactive. Reactive creates a deep comparison. If we're creating a reactive string, or a Boolean, or other primitive, then we would use ref, but if we want something that we want to be deeply the same, such as an object or an array, we use the reactive property instead.

[0:35] Let's start building our form. We're going to need a div, which is going to have a class of form-field. Inside that class, we'll have a label. The first one we'll do is craft-name. Let's have the input, which is going to have an ID, which is the same with our previous term. Then, we're going to bind with v-model, the value of updateFields.name.

[1:03] If we look at our v-model and go to our CraftView and our update form, we'll see that we've got this updateFields variable here. As I change the value of my form, it's changing in my updateFields as well. Let's do the same for the rest of the fields. Let's have a look. Brilliant.

[1:38] Let's add a little bit of styling. Now our form is reactive. If we change anything in these update fields, it's updating in our form. Next, we want to send this data to our GraphQL endpoint to update it.