v-model
指令在表单元素上创建双向数据绑定,它负责用于监听用户输入事件以更新数据
注意,v-model
会忽略所有表单元素特性的初始值,而总是将 Vue 实例的数据作为数据来源
1、输入框
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input v-model="message" placeholder="请输入内容"> <span>输入的值为: {{ message }}</span> </div> <script> new Vue({ el: '#app', data: { message: '' // string 类型 } }) </script> </body> </html>
2、单选按钮
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="radio" id="apple" value="Apple" v-model="picked"> <label for="apple">Apple</label> <br> <input type="radio" id="orange" value="Orange" v-model="picked"> <label for="orange">Orange</label> <br> <span>选中的值为: {{ picked }}</span> </div> <script> new Vue({ el: '#app', data: { picked: '' // string 类型 } }) </script> </body> </html>
3、复选框
- 单个复选框
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="checkbox" id="bool" v-model="checked"> <label for="bool">{{ checked }}</label> </div> <script> new Vue({ el: '#app', data: { checked: false // boolean 类型 } }) </script> </body> </html>
- 多个复选框
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="checkbox" id="apple" value="Apple" v-model="checked"> <label for="apple">Apple</label> <input type="checkbox" id="orange" value="Orange" v-model="checked"> <label for="orange">Orange</label> <br> <span>选择的值为: {{ checked }}</span> </div> <script> new Vue({ el: '#app', data: { checked: [] // array 类型 } }) </script> </body> </html>
4、选择框
- 单选
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <select v-model="selected"> <option disabled value="">请选择</option> <option>Apple</option> <option>Orange</option> </select> <span>选择的值为: {{ selected }}</span> </div> <script> new Vue({ el: '#app', data: { selected: '' // string 类型 } }) </script> </body> </html>
- 多选
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <select multiple v-model="selected"> <option>Apple</option> <option>Banana</option> <option>Cherry</option> <option>Durian</option> <option>Orange</option> </select> <span>选择的值为: {{ selected }}</span> </div> <script> new Vue({ el: '#app', data: { selected: [] // array 类型 } }) </script> </body> </html>
5、修饰符
.lazy
:默认情况下,input 事件触发后同步数据,使用.lazy
可指定 change 事件触发后同步数据
<input v-model.lazy="msg" >
.number
:将用户输入的值自动转换为数值类型
<input v-model.number="age" type="number">
.trim
:将用户输入的值过滤掉首位空白字符
<input v-model.trim="msg">
文章知识点与官方知识档案匹配,可进一步学习相关知识