<四>v-model 双向绑定表单操作
v-model 用于表单控件的双向绑定。实际上就是对html控件的value值进行操作的一个命令
作用于带value的控件,比如input,selected,textarea等。
1、input(text) 、textarea
<body> <div id="app"> <input type="text" v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
</div> <script src="vue.js"></script> <script> var app = new Vue({ el: '#app', data: { message: '', }, }); </script>
2、input(checkbox) 复选框
<body> <div id="app"> <p>多个复选框:</p> <input type="checkbox" id="runoob" value="Runoob" v-model="messages"> <label for="runoob">Runoob</label> <input type="checkbox" id="google" value="Google" v-model="messages"> <label for="google">Google</label> <input type="checkbox" id="taobao" value="Taobao" v-model="messages"> <label for="taobao">taobao</label> <p>checkMessage is: {{ messages }}</p> </div> <script src="vue.js"></script> <script> var app = new Vue({ el: '#app', data: { messages: [], }, }); </script>
3、input(radio) 单选按钮
<body> <div id="app"> <input type="radio" id="runoob" value="Runoob" v-model="messages"> <label for="runoob">Runoob</label> <input type="radio" id="google" value="Google" v-model="messages"> <label for="google">Google</label> <input type="radio" id="taobao" value="Taobao" v-model="messages"> <label for="taobao">taobao</label> <p>checkMessage is: {{ messages }}</p> </div> <script src="vue.js"></script> <script> var app = new Vue({ el: '#app', data: { messages: 'Taobao', }, }); </script>
4、selected 下拉框
<body> <div id="app"> <select v-model="selected"> <option disabled value="">请选择</option> <option value ='a'>A</option> <option value='b'>B</option> <option value='c'>C</option> </select> <span>Selected: {{ selected }}</span> </div> <script src="vue.js"></script> <script> var app = new Vue({ el: '#app', data: { selected: 'a', }, }); </script>
5、绑定修饰符
<body> <div id="app"> <input v-model.lazy="msg"> <!-- //从实时触发变成change时同步,即焦点离开此控件时触发 --> <input v-model.number="age" type="number"> <!-- //将变量转成数字型,如果转换失败,则返回原来的值 --> <input v-model.trim="msg"> <p> {{msg}}</p> </div> <script src="vue.js"></script> <script> var app = new Vue({ el: '#app', data: { msg: '', age:1, }, }); </script>