DEV Community

Cover image for What is the utility of the v-model directive?
Leonardo Cunha
Leonardo Cunha

Posted on • Updated on

What is the utility of the v-model directive?

Definition

Looking through the documentation v-model is a directive that can be used to:

"Create a two-way binding on a form input element or a component".

This allows creating a data relation between the data object of your component and some other component or an HTML element, like a form input.

Nice! But why is that useful?

Because it allows you to make quick value updates in your component. Without the need to use states, props, or anything like that. And is a "two-way binding", allowing significant data manipulation in your component.

Example

Let's see a quick example:
HTML:

<div id="app">
  <input v-model="checkedNames" type="checkbox" id="kirk" value="John"/>
  <label for="kirk"> Kirk</label>

  <input v-model="checkedNames" type="checkbox" id="spock" value="Paul"/>
  <label for="spock"> Spock</label>

  <input v-model="checkedNames" type="checkbox" id="mcCoy" value="George"/>
  <label for="mcCoy"> McCoy</label>

  <input v-model="checkedNames" type="checkbox" id="uhura" value="Ringo"/>
  <label for="uhura"> Uhura</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

body {
  font-family: 'Bitter', serif;
}

#app {
  text-align: center;
  padding: 70px;
  max-width: 360px;
  font-size: 16px;
  margin: 0 auto;
  display: table;
  line-height: 2em;
}

label {
  padding-right: 10px;
}
Enter fullscreen mode Exit fullscreen mode

JavaScript:

const App = {
  data() {
    return {
      checkedNames: []
    }
  }
}

Vue.createApp(App).mount('#app')
Enter fullscreen mode Exit fullscreen mode

See how in each input tag, the v-model directive manipulates the DOM and appends the value in each label into the array from the input to the data component object (one-way bidding). And after that, send the array updated with the values to the span tag(two-way binding).

Awesome, right?

Restrictions

As explained in the documentation, the v-model directive has its use limited to the following elements:

<input>
<select>
<textarea>
<components>
Enter fullscreen mode Exit fullscreen mode

Acknowledgment

I must thank @sarah_edo for the great example in her CodePen.

Top comments (0)