1、v-model的使用原理。
<body>
<div id="root">
<input type="text" :value="msg" @input="changeMsg">
<h2>{{msg}}</h2>
</div>
<script>
const vm = new Vue({
el:"#root",
data(){
return {
msg:"张三"
}
},
methods:{
changeMsg(e){
this.msg = e.target.value
}
}
})
</script>
</body>
2.v-model与radio结合使用
<body>
<div id="root">
<label for="male">男</label>
<input type="radio" name="sex" id="male" v-model="sex" value="男">
<label for="female">女</label>
<input type="radio" name="sex" id="female" v-model="sex" value="女">
<h3>您的性别是:{{sex}}</h3>
</div>
<script>
const vm = new Vue({
el: "#root",
data() {
return {
sex: "男"
}
}
})
</script>
</body>
3.v-model与checkbox结合使用
<body>
<div id="root">
<label for="isagree"><input type="checkbox" id="isagree" :checked="isagree"
@click="btn">同意协议</label><br>
<button :disabled="!isagree">下一步</button>
</div>
<script>
const vm = new Vue({
el:"#root",
data(){
return {
isagree:false
}
},
methods:{
btn(){
this.isagree = !this.isagree
}
}
})
</script>
</body>
<body>
<div id="root">
<h2>多选框</h2>
<input type="checkbox" name="sports" value="篮球" v-model="hobbies">篮球
<input type="checkbox" name="sports" value="足球" v-model="hobbies">足球
<input type="checkbox" name="sports" value="羽毛球" v-model="hobbies">羽毛球
<input type="checkbox" name="sports" value="排球" v-model="hobbies">排球
<h2>您的爱好是:{{hobbies}}</h2>
</div>
<script>
const vm = new Vue({
el:"#root",
data(){
return {
hobbies:[]
}
}
})
</script>
</body>
<body>
<div id="root">
<label :for="index" v-for="(item,index) in sports" >
<input type="checkbox" name="sport" :id="index" :value="item" v-model="hobbies">{{item}}
</label>
<h2>您的爱好是:{{hobbies}}</h2>
</div>
<script>
const vm = new Vue({
el:"#root",
data(){
return {
hobbies:[],
sports:['篮球','足球','羽毛球','排球']
}
}
})
</script>
</body>
4.v-model与select结合使用
<body>
<div id="root">
<!-- 单选 -->
<select name="fruit" v-model="fruit">
<option :value="item" v-for="(item,index) in fruits">{{item}}</option>
</select>
<h2>你选择的水果是:{{fruit}}</h2>
<!-- 多选 -->
<select name="fruits" v-model="fruits2" multiple>
<option :value="item" v-for="(item,index) in fruits">{{item}}</option>
</select>
<h2>你选择的水果是:{{fruits2}}</h2>
</div>
<script>
const vm = new Vue({
el:"#root",
data(){
return {
fruits:['苹果','香蕉','西瓜'],
fruit:"苹果",
fruits2:[]
}
}
})
</script>
</body>
5.v-model修饰符
lazy
<body>
<div id="root">
<input type="text" v-model.lazy="msg">
<h2>{{msg}}</h2>
</div>
<script>
const vm = new Vue({
el: "#root",
data() {
return {
msg: '张三',
age: 18,
name: '李四'
}
}
})
</script>
</body>
不是实时修改,按下enter键后才会修改。
number
<input type="text" v-model.number="age">
<h2>{{age}}---{{typeof age}}</h2>
必须是数字,不是数字不显示。
trim
<input type="text" v-model.trim="name">
<h2>姓名:{{name}}</h2>
去除空格