Using Vue. js to realize the effect of all selection and reverse selection of checkbox
- 2021-07-12 05:04:44
- OfStack
Preface
This article mainly shares with you the effect of using Vue. js to realize the all-selection and anti-selection of checkbox. There is an bug in the code written before, that is, when you choose all-selection, remove the following one option, and then click all-selection and the result is anti-selection. Later, I am very grateful to my friend for leaving a message to help me change this problem. Let's take a look at how to realize it.
html sample code
<template>
<div>
<input type='checkbox' class='input-checkbox' v-model='checked' v-on:click='checkedAll'> All selection
<template v-for='checkb in checkboxData'>
<input type='checkbox' name='checkboxinput' class='input-checkbox' v-model='checkboxModel' value='{{checkb.id}}'>{{checkb.value}}
</template>
</div>
</template>
js sample code
<script>
export default {
methods:{
checkedAll: function() {
var _this = this;
console.log(_this.checkboxModel);
if (this.checked) {// Realize reverse selection
_this.checkboxModel = [];
}else{// Realize all selection
_this.checkboxModel = [];
_this.checkboxData.forEach(function(item) {
_this.checkboxModel.push(item.id);
});
}
}
},
watch: {// Depth watcher
'checkboxModel': {
handler: function (val, oldVal) {
if (this.checkboxModel.length === this.checkboxData.length) {
this.checked=true;
}else{
this.checked=false;
}
},
deep: true
}
},
data () {
return {
checkboxData:[{
id:'1',
value:' Apple '
},{
id:'2',
value:' Litchi '
},{
id:'3',
value:' Banana '
},{
id:'4',
value:' Dragon fruit '
}],
checkboxModel:['1','3','4'],
checked:""
}
}
}
</script>
watch
Type: Object
Details:
1 object, the key is the observation expression, and the value is the corresponding callback. The value can also be a method name or an object containing options. Called for each key at instantiation time
$watch()
.
Example:
var vm = new Vue({
data: {
a: 1
},
watch: {
'a': function (val, oldVal) {
console.log('new: %s, old: %s', val, oldVal)
},
// Method name
'b': 'someMethod',
// Depth watcher
'c': {
handler: function (val, oldVal) { /* ... */ },
deep: true
}
}
})
vm.a = 2 // -> new: 2, old: 1
Summarize
The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.