表单绑定 v-model
Vue使用v-model实现表单元素和数据的双向绑定。
v-model 本质是个语法糖,实质包含2个操作
- 1. v-bind:绑定value属性值
- 2. v-on 给当前元素绑定input事件
<input type="text" v-model = "message">
=>
<input type="text" v-bind:value="message" v-on:input="message = $event.target.value">
v-model 作用于 radio
<body>
<div id="app">
<label for="male">
<input type="radio" id="male" value="男" v-model="sex">男
</label>
<label for="female">
<input type="radio" id="female" value="女" v-model="sex">女
</label>
<h2>您选择的性别是:{{sex}}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
sex: '男'
}
})
</script>
</body>
v-model 作用于 checkbox(单选)
<body>
<div id="app">
<label for="agree">
<input type="checkbox" id="agree" v-model="isAgree">同意协议
</label>
<br/><br/>
<button :disabled="!isAgree">下一步</button>
<h2>您选择的是:{{isAgree}}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
isAgree: false
}
})
</script>
</body>
v-model 作用于 checkbox(多选)
<body>
<div id="app">
<input type="checkbox" value="篮球" v-model="hobbies">篮球
<input type="checkbox" value="足球" v-model="hobbies">足球
<input type="checkbox" value="羽毛球" v-model="hobbies">羽毛球
<input type="checkbox" value="乒乓球" v-model="hobbies">乒乓球
<h2>您选择的是:{{hobbies}}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
hobbies: []
}
})
</script>
</body>
:value值绑定,动态加载数据
<body>
<div id="app">
<label v-for="item in hobbies">
<input type="checkbox" :value="item">{{item}}
</label>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
hobbies: ['篮球','足球', '乒乓球', '羽毛球']
}
})
</script>
</body>
v-model 作用于 select (单选)
<body>
<div id="app">
<select name="fruit" id="fruit" v-model="fruit">
<option value="apple">apple</option>
<option value="pear">pear</option>
<option value="banana">banana</option>
</select>
<h2>您选择的是:{{fruit}}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
fruit: 'pear'
}
})
</script>
v-model 作用于 select (多选)
<body>
<div id="app">
<select name="fruit" id="fruits" v-model="fruits" multiple>
<option value="apple">apple</option>
<option value="pear">pear</option>
<option value="banana">banana</option>
</select>
<h2>您选择的是:{{fruits}}</h2>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
fruits: []
}
})
</script>
</body>