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 use to:

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

Which in other words, allows you to kinda create 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 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 a great manipulation of data in your component.

hades-thumps-up

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 biding). And after that, send the array updated with the values to the span tag(two-way biding)?

Awesome, right?

spock-fascinating

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'll like to thank @sarah_edo, for the great example provided in her CodePen.

Discussion (0)