使用v-model指令对表单数据自动收集
- text/textarea
- radio
- checkbox
- select
实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--view-->
<div id="app">
<form action="/×××" @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="basketbal" value="basketbal" v-model="likes"><label for="basketbal">篮球</label>
<input type="checkbox" id="football" value="football" v-model="likes"><label for="football">足球</label>
<input type="checkbox" id="pingpong" value="pingpong" v-model="likes"><label for="pingpong">乒乓球</label><br>
<span>城市:</span>
<select v-model="cityId">
<option value="">未选择</option>
<option v-for="(city, index) in cities" :key="index" :value="city.id">{{city.name}}</option>
</select><br>
<span>介绍:</span>
<textarea rows="10" v-model="desc"></textarea><br>
<input type="submit" value="注册" />
</form>
</div>
<!--1.引入Vue-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
// 2.创建Vue实例
const vm = new Vue({
// 配置对象
el: '#app', // element:选择器
data: { // 数据(model)
username: '',
pwd: '',
sex: '女',
likes: [],
cities: [
{id: 1, name: 'BJ'},
{id: 2, name: 'SH'},
{id: 3, name: 'GZ'},
{id: 4, name: 'SZ'}
],
cityId: '',
desc: ''
},
methods: {
handleSubmit () {
console.log(this.username, this.pwd)
}
}
})
</script>
</body>
</html>
1.点击注册按钮时,不提交表单
<form action="/×××" @submit.prevent="handleSubmit">
2.单选框默认值
单选框默认值默认为“女”,也可修改默认值。即:修改data中的sex值。如果不设定默认值,可以这样设置(sex设为空):
data{
sex: ''
}
3.复选框默认值
复选空没有设置默认人。可以这样设置默认值:
data{
likes: ['football']
}
【注意】:单选框、复选框、下拉列表的默认值设定必须和value中对应的值一样