The v-model Vue directive allows us to create two-way bindings. Learn how to use it
Thisv-model
Vue 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>
<option>Apple</option>
<option>Banana</option>
<option>Strawberry</option>
</select>
<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.lazy
Not justv.model
.
Use input fields,v-model.trim
Very 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:
<template>
<div class="">
<h1>Add Product</h1>
<label>Name</label>: <input>
<label>Description</label>: <textarea></textarea>
<button @click="addProduct">Add</button>
</div>
</template>
<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 formproduct
Status value, you useproduct.*
:
<label>Name</label>: <input v-model="product.name">
<label>Description</label>: <textarea v-model="product.description"></textarea>
Download mine for freeVue manual
More vue tutorials:
- Vue.js overview
- Vue.js CLI: Learn how to use it
- Vue.js development tools
- Configure VS code for Vue development
- Create your first application with Vue.js
- Vue.js single file component
- Vue.js templates and interpolation
- Vue.js instructions
- Vue.js method
- Vue.js calculated attributes
- Use CSS to style Vue.js components
- Vue.js observer
- Vue method vs observer vs calculated property
- Vue.js filter
- Vue.js components
- Vue.js slot
- Vue.js component props
- Vue.js activities
- Vue.js component communication
- Vuex, Vue.js state manager
- Vue, use a component inside another component
- Vue, how to use prop as a class name
- How to use SCSS with Vue.js single file component
- Use Tailwind in Vue.js
- Vue router
- Dynamically display Vue components
- Vue.js cheat sheet
- Use Vuex to store Vue data to localStorage
- How to use Vue dynamic application class
- Vue, how to use the v model
- Vue, why data must be functions
- Roadmap to become a Vue.js developer in 2020