<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="app">
<input type="checkbox" v-model="checkedAll" id="all" @click="selectAll()">
<label for="all">全选:</label>
<br>
<hr/>
<template v-for="(item, index) in list">
<input type="checkbox" :value="item.value" :id="item.value" v-model="checked" />
<label :for="item.value">{{ item.label }}</label>
<br>
</template>
<br>
<p>选择了:{{ checked }}</p>
</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
checked:[],
checkedAll:false,
list:[
{
id:1,
value:'javascript',
label:'JavaScript'
},{
id:2,
value:'html',
label:'HTML'
},{
id:3,
value:'css',
label:'CSS'
}]
},
methods:{
selectAll:function(){
if(this.checkedAll){
// 全不选
this.checked = [];
}else{
// 全选
this.checked = [];
this.list.forEach((item)=>{
this.checked.push(item.value);
})
}
}
},
watch:{
checked: function(){
let self = this;
if(this.checked.length === this.list.length){
self.checkedAll = true;
} else{
self.checkedAll = false;
}
}
}
})
</script>
</body>
</html>
Description:
- Whether or not the checkbox is checked box according to v-model (Example bindings on the checked) and the value to, for example, if the checked = 'html', the value = 'html' is selected.
- Using the v-for = "item in list" is bound to input the item above, to use: (colon syntactic sugar binding)
- watch is a change in the value of listeners (checked), did not change once executed once
// 注:复选框还可以规定不成功的值
<input type="checkbox" v-model="toggle" :true-value="value1" :false-value="value2">
<label>复选框</label>
<script>
const app = new Vue({
el:'#app',
data: {
toggle: false,
value1: 'a',
value2: 'b'
}
})
</script>
// 勾选时:app.toggle === app.value1; 未勾选时,app.toggle === app.value2
Reference "Vue.js real" P58 ~ P59