Create a Two Way Binding to Update Data Throughout an App with Vue v-model

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

We'll see how we can define two-way binding using the v-model directive. This allows us to update data in our component and have it change the data stored in the application. This is particularly useful in forms within our application.

We'll see a form in action by creating a message data prop and binding the input field to that data prop and watch the data get updated. If this prop is updated anywhere in the application it will affect the input that we defined.

Instructor: [0:00] So far, we've bound data from our props into our elements in our HTML. We've seen that we can operate on those props, but we've also seen that so far, any edits that we make, any transformations we make on the data here are not reflected in the data source.

[0:17] If we want to create a two-way data binding so that when data's updated in the DOM it's also being updated in our prop, we use the Vue directive, v-model. Let's test that with an input box. Let's v-model with a variable that we can call message. We'll have a placeholder that says, edit me. Below that, let's say in the input box says, message.

[0:46] Here we go. As we change this, nothing's changing. That's because we haven't introduced the variable. Let's set message to initialize as an empty string, and then let's try again to both sides.

[1:04] As my input box is changing, the value is changing, and then that is what's being rendered here. We can see that in the tools. We keep an eye on message here. As I change the message, it's being updated in my data prop and on my DOM.

[1:24] Because it's got two-way data binding, if that prop gets updated by some other part of my application, it will also be updated in every place where it's being used. It's being bound in both directions. This is helpful for form inputs, and in any other situation where you want the data in the browser to reflect and be able to impact the data that's held in the Vue model.