Vue, how to use the v model

The v-model Vue directive allows us to create two-way bindings. Learn how to use it

Thisv-modelVue instructions allow us to create two-way bindings.

You can bind a form input element, for example, when the user changes the content of the field, make it change the Vue data attributes:

<input v-model="message" placeholder="Enter a message">
<p>Message is: {{ message }}</p>
<select v-model="selected">
  <option disabled value="">Choose a fruit</option>
<span>Fruit chosen: {{ selected }}</span>

Convenient command modifiers

To update the model when a change event occurs (rather than every time the user presses a key), you can usev-model.lazyNot justv.model.

Use input fields,v-model.trimVery useful because it will automatically remove spaces.

If you accept numbers instead of strings, make sure to usev-model.number.

Nested attributes

Suppose you have a shopping cart, and you have a component that contains a form for adding products:

  <div class="">
    <h1>Add Product</h1>
    <label>Name</label>: <input>
    <label>Description</label>: <textarea></textarea>
    <button @click="addProduct">Add</button>

<script> export default { name: ‘AddProduct’, data() { return { product: { name: ‘’, description: ‘’ } } }, methods: { addProduct() { console.log(this.product) } } } </script>

In order to update the internal properties of the formproductStatus value, you useproduct.*:

<label>Name</label>: <input v-model="">
<label>Description</label>: <textarea v-model="product.description"></textarea>

Download mine for freeVue manual

More vue tutorials: