vue_表单控件

时间:2022-05-17 20:21:59

Vue.js中提供 v-model 的指令对表单元素进行双向数据绑定,在修改表单元素值的同时,实例 vm 中对应的属性值也同时更新,反之亦然。本小节介绍主要input元素绑定v-model 后的具体用法和处理方式,实例所依赖的js代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="lib/bootstrap.min.css">
<script src="lib/jquery-1.7.2.js"></script>
<script src="lib/bootstrap.js"></script> <script src="vue2.0.js"></script>
<script src="vue-resource.js"></script>
<script>
window.onload = function(){
var vm = new Vue({
el : '.container',
data : {
message:'',
picked:'Runoob',//radio 默认选择男
checked:'',
multiChecked:[],
selected:'A', //option 默认选择A
multiSelected:[]
},
methods:{
add:function(){
// alert(this);
//添加数据到数组里面 this.myData.push({
name : this.username,
age : this.age,
});
//添加完后清空input
this.username = '';
this.age = '';
},
deletMsg : function(n){
if(n == -2){
this.myData = [];
}else{
this.myData.splice(n,1);//删除某一条数据
}
}
}
});
} </script>
</head>
<body>
<div class="container">
<form role="form">
<div class="form-group">
<h2>1. Text 输入框示例</h2>
<input type="text" class="form-control" v-model="message">
<span>Your input is : {{ message }}</span>
</div>
<div class="form-group">
<h2>2. Radio 单选框示例</h2>
<input type="radio" id="runoob" value="Runoob" v-model="picked">
<label for="runoob">Runoob</label>
<br>
<input type="radio" id="google" value="Google" v-model="picked">
<label for="google">Google</label>
<br>
<span>选中值为: {{ picked }}</span>
<!-- picked值为选中的radio元素的value值 -->
</div>
<div class="form-group">
<h2>3.Checkbox </h2>
<h4>Checkbox 分两种情况:单个勾选和多个勾选框</h4>
<h5>单个勾选框:v-model即为布尔值,此时input的value并不影响v-model的值</h5>
<input type="checkbox" v-model="checked">
<span>checked:{{ checked }}</span>
<h5>多个勾选框:v-model使用相同的属性名称,此属性为数组</h5>
<label for=""><input type="checkbox" value="1" v-model="multiChecked">1</label>
<label for=""><input type="checkbox" value="2" v-model="multiChecked">2</label>
<label for=""><input type="checkbox" value="3" v-model="multiChecked">3</label>
<label for=""><input type="checkbox" value="4" v-model="multiChecked">4</label>
<label for=""><input type="checkbox" value="5" v-model="multiChecked">5</label>
<label for=""><input type="checkbox" value="6" v-model="multiChecked">6</label>
<p>MultiChecked : {{ multiChecked.join(',') }}</p>
</div>
<div class="form-group">
<h2>4. Select</h2>
<h4>Select 分两种情况:单选和多选,多选的时候需要绑定到一个数组</h4>
<h5>单选:</h5>
<select name="" id="" v-model="selected">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<span>Selected: {{ selected }}</span>
<h5>多选:</h5>
<select name="" id="" v-model="multiSelected" multiple>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
</select>
<span>Selected: {{ multiSelected }}</span>
</div>
</form>
</div>
</body>
</html>