Handling Forms
The Basics
You can use the v-model
directive to create two-way data bindings on form input elements. It automatically picks the correct way to update the element based on the input type.
Example
1 | <form id="demo"> |
1 | new Vue({ |
Result
Lazy Updates
By default, v-model
syncs the input with the data after each input
event. You can add a lazy
attribute to change the behavior to sync after change
events:
1 | <!-- synced after "change" instead of "input" --> |
Casting Value as Number
If you want user input to be automatically persisted as numbers, you can add a number
attribute to your v-model
managed inputs:
1 | <input v-model="age" number> |
Dynamic Select Options
When you need to dynamically render a list of options for a <select>
element, it’s recommended to use an options
attribute together with v-model
:
1 | <select v-model="selected" options="myOptions"></select> |
In your data, myOptions
should be an keypath/expression that points to an Array to use as its options. The Array can contain plain strings, or contain objects.
The object can be in the format of {text:'', value:''}
. This allows you to have the option text displayed differently from its underlying value:
1 | [ |
Will render:
1 | <select> |
Alternatively, the object can be in the format of { label:'', options:[...] }
. In this case it will be rendered as an <optgroup>
:
1 | [ |
Will render:
1 | <select> |
Input Debounce
The debounce
param allows you to set a minimum delay after each keystroke before an update is executed. This can be useful when you are performing expensive operations on each update, for example making an Ajax request for type-ahead autocompletion.
1 | <input v-model="msg" debounce="500"> |
Result
Next: Computed Properties.