Vue指令
v-model
v-model指令用于在input、select、text、checkbox、radio等表单空间元素上创建双向数据绑定。根据控件类型v-model自动选取正确的方法更新元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-model</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<form action="#">
姓名:<input type="text" v-model="data.name"><br/>
性别:
<input type="radio" id="man" value="man" v-model="data.sex">
<label for="man">男</label>
<input type="radio" id="woman" value="woman" v-model="data.sex">
<label for="woman">女</label><br/>
兴趣:
<input type="checkbox" id="book" value="book" v-model="data.interest">
<label for="book">阅读</label>
<input type="checkbox" id="swim" value="swim" v-model="data.interest">
<label for="swim">游泳</label>
<input type="checkbox" id="running" value="running" v-model="data.interest">
<label for="running">跑步</label>
<input type="checkbox" id="song" value="song" v-model="data.interest">
<label for="song">唱歌</label><br/>
身份:
<select v-model="data.identify">
<option value="teacher" selected>教师</option>
<option value="doctor">医生</option>
<option value="lawyer">律师</option>
</select>
</form>
<h3>您的姓名:{{data.name}}</h3>
<h3>性别:{{data.sex}}</h3>
<h3>爱好:{{data.interest}}</h3>
<h3>身份:{{data.identify}}</h3>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
data: {
name: '',
sex: '',
interest: [],
identify: ''
}
}
})
</script>
</body>
</html>
指令参数
在v-model指令之后还可添加多个参数.number、.lazy、.trim
number
.number
使用修饰符number可以将输入转换为Number类型,否则虽然输入的数字,但它的类型其实是String类型
不加number的效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>number</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<!--即便这里的类型是number但是输入后的类型变成了string-->
<input type="number" v-model="message">
<p>{{typeof message}}</p>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
message: 123
}
})
</script>
</body>
</html>
加上number的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>number</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<input type="number" v-model.number="message">
<p>{{typeof message}}</p>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
message: 123
}
})
</script>
</body>
</html>
lazy
.lazy
在输入框中,v-model默认是在input事件中同步输入框的数据,使用修饰符.lazy会转变为change事件中同步
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>lazy</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model.lazy="message">
<p>{{message}}</p>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
message: ''
}
})
</script>
</body>
</html>
注意:message并不是实时更新的,而是在失焦或按回车时才更新
trim
.trim
修饰符.trim可以自动过滤输入的首位空格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>trim</title>
<script src="../js/vue.min.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model.trim="message">
<p>{{message}}</p>
</div>
<script>
let app = new Vue({
el: '#app',
data: {
message: ''
}
})
</script>
</body>
</html>