Vue框架--表单元素默认被选中
我们都知道复选框在前端开发中的重要性,可以说,到处都在使用,最近在学习vue,看了vue的处理方式,感觉尤大大太牛了。这里总结一下表单默认被选中的操作
对于单选按钮radio,如果想默认选中“女”或者“男”,只需在data数据里操作input所绑定的v-model即可,代码如下
new Vue({
el: "#demo",
data: {
sex: '男'
}
对于复选框checkbox,如果想默认选中某一个选型,只需在data数据里操作input所绑定的v-model即可,代码如下
<span>爱好:</span>
<input type="checkbox" id="basketball" value="basket" v-model="likes">
<label for="basketball">篮球</label>
<input type="checkbox" id="football" value="foot" v-model="likes">
<label for="football">足球</label>
<input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
<label for="pingpang">乒乓</label><br>
new Vue({
el: "#demo",
data: {
likes: ['foot'],
}
对于下拉框select,如果想默认选中某一选项,只需在data数据里直接操作select所绑定的v-model即可,代码如下
new Vue({
el: "#demo",
data: {
allCitys: [{
id: 1,
name: 'BJ'
}, {
id: 2,
name: 'SH'
}, {
id: 3,
name: 'GZ'
}],
cityId: '2'
}
上一段完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--
1. 使用v-model(双向数据绑定)自动收集数据
text/textarea
checkbox
radio
select
-->
<div id="demo">
<form action="/xxx" @submit.prevent="handSubmit">
<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="basketball" value="basket" v-model="likes">
<label for="basketball">篮球</label>
<input type="checkbox" id="football" value="foot" v-model="likes">
<label for="football">足球</label>
<input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
<label for="pingpang">乒乓</label><br>
<span>城市:</span>
<select name="" id="" v-model="cityId">
<option value="">未选择</option>
<option :value="city.id" v-for="(city, index) in allCitys" :key="index">{
{city.name}}</option>
</select><br>
<span>介绍</span>
<textarea name="" id="" cols="30" rows="10" v-model="desc"></textarea><br>
<input type="submit" value="注册">
</form>
</div>
<script src="js/vue.js"></script>
<script>
new Vue({
el: "#demo",
data: {
username: '',
pwd: '',
sex: '',
likes: ['foot'],
allCitys: [{
id: 1,
name: 'BJ'
}, {
id: 2,
name: 'SH'
}, {
id: 3,
name: 'GZ'
}],
cityId: '2',
desc: ''
},
methods: {
handSubmit() {
console.log(this.username, this.pwd);
}
},
})
</script>
</body>
</html>
效果如下
学习了几天vue,感觉这个框架太牛了,会节省很多时间,但还是要好好学习原生js啊,加油,年轻人!