本文将介绍复选框(checkbox)的双向绑定,例如:
<input type="checkbox" id="checkbox" v-model="checked">
或者
<input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
注意,如果只有一个复选框,可以将复选框绑定到单个布尔值。如果存在多个复选框,可以将它绑定到同一个数组。
下面将介绍怎样将单个复选框绑定到一个布尔值,例如:
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue</title>
<!-- 使用 CDN 引入 Vue 库 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="checkbox" id="checkbox" v-model="checked">
<label for="checkbox">{{ checked }}</label>
</div>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
// 绑定到复选框的属性
checked: false
}
});
</script>
</body>
</html>运行效果:

下面将介绍怎样将多个复选框绑定到一个数组,例如:
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue</title>
<!-- 使用 CDN 引入 Vue 库 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" id="john" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
// 绑定到复选框的数组属性
// 当我们选中复选框时,该数组存储的 value 的内容
checkedNames: []
}
});
</script>
</body>
</html>运行效果:
