我们可以用 v-model 指令在表单 input 及 textarea 元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。
文本输入框
<!-- 你可以通过变量message取到输入到文本框中的值 --><input v-model="message"><p>你输入的内容: {{ message }}</p>多行文本框<!-- 注意这里如果在文本区域插值 (<textarea></textarea>) 并不会生效 --><textarea v-model="message"></textarea><p>你输入的内容:{{ message }}</p>单选框<!-- 变量sex就是选中项的对应的value值 --><template><div id="radio"> <input type="radio" id="male" value="男" v-model="sex"> <label for="male">男</label> <br> <input type="radio" id="female" value="女" v-model="sex"> <label for="female">女</label> <br> <span>选择的性别: {{ sex }}</span></div></template><script>new Vue({ el: '#radio', data: { sex: '男' // 使默认选中'男' }})</script>
多选框
<template><div id='checkbox'> <input type="checkbox" id="apple" value="苹果" v-model="fruit"> <label for="apple">苹果</label> <input type="checkbox" id="orange" value="桔子" v-model="fruit"> <label for="orange">桔子</label> <input type="checkbox" id="banana" value="香蕉" v-model="fruit"> <label for="banana">香蕉</label> <br> <span>选中喜欢的水果: {{ fruit }}</span></div></template><script>new Vue({ el: '#checkbox', data: { fruit: ['香蕉'] // 使默认选中'香蕉' }})</script>
下拉单选框
<!-- 变量city就是你下拉选择项的value值 --><template><div id="select"> <select v-model="city"> <option disabled value="">请选择</option> <option>北京</option> <option>上海</option> <option>广州</option> <option>深圳</option> <option>杭州</option> </select> <span>你选中的城市: {{ city }}</span></div></template><script>new Vue({ el: '#select', data: { selected: '' // 使默认选择'请选择' }})</script>
下拉多选框
<!-- 下拉选项是动态渲染出来的,而且这里添加multiple表示下拉多选,那么city对应的值将会是数组的形式 --><template><div id="multiple-select"> <select v-model="city" multiple> <option v-for="option in options" v-bind:value="option.value"> {{ option.text }} </option> </select> <span>你选中的城市: {{ city }}</span></div></template><script>new Vue({ el: '#multiple-select', data: { options: [ { text: '北京', value: '北京' }, { text: '上海', value: '上海' }, { text: '广州', value: '广州' }, { text: '深圳', value: '深圳' }, { text: '杭州', value: '杭州' } ], selected: [] }})</script>
总结
这节我们学习了HTML
中表单的单行文本框、多行文本框、单选框、多选框、下拉单选框、下拉多选框等元素在vue.js
中的数据绑定,同时也学习了通过给绑定的变量赋值来控制表单元素的默认值,很简单吧。