vuejs中使用v-model对表单数据的收集
表单收集的信息针对有text/textarea,checkbox,radio,select
举个例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>08_表单输入绑定</title> </head> <body> <div id="demo"> <form action="/xxx" @submit.prevent="handleSubmit"> <span>用户名: </span> <input type="text" v-model="username"><br> <span>密码: </span> <input type="password" v-model="pwd"><br> <span>性别: </span> <input type="radio" id="female" value="女" v-model="sex"> <label for="female">女</label> <input type="radio" id="male" value="男" v-model="sex"> <label for="male">男</label><br> <span>爱好: </span> <input type="checkbox" id="basket" value="basket" v-model="likes"> <label for="basket">篮球</label> <input type="checkbox" id="foot" value="foot" v-model="likes"> <label for="foot">足球</label> <input type="checkbox" id="pingpang" value="pingpang" v-model="likes"> <label for="pingpang">乒乓</label><br> <span>城市: </span> <select v-model="cityId"> <option value="">未选择</option> <option :value="city.id" v-for="(city, index) in allCitys" :key="city.id">{{city.name}}</option> </select><br> <span>介绍: </span> <textarea rows="10" v-model="info"></textarea><br><br> <input type="submit" value="注册"> </form> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript"> new Vue({ el: '#demo', data: { username: '', pwd: '', sex: '男', likes: ['foot'], allCitys: [{id: 1, name: 'BJ'}, {id: 2, name: 'SS'}, {id: 3, name: 'SZ'}], cityId: '', info: '' }, methods: { handleSubmit () { console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info) alert('提交注册的ajax请求') } } }) </script> </body> </html>
运行结果:
提示点:
1.参考官方文档: https://cn.vuejs.org/v2/guide/forms.html#%E5%9F%BA%E7%A1%80%E7%94%A8%E6%B3%95
2.城市选择时,当选中时,vm.cityId == vm.city.id,依据
3.:key 到底有什么用?按照文档中的意思是:
一个列表项要有一个key值,这个key值如果唯一且未发生变化,则dom就会被复用,反之则需要重新生成。