I want to check a list of checkboxes when change a v-switch. What I have is this:
This is switch component, if selectAll is true I want to check all checkboxes:
<v-switch style="padding-right:15px;" v-model="selectAll" @change="handleChanging">
</v-switch>
Here is the list, each item has a checkbox before:
<v-list-item v-for="(item, index) in itemsEducators" :key="index">
<v-list-item-action>
<v-checkbox :key="item.title" :input-value="item.checked"> </v-checkbox>
</v-list-item-action>
<v-list-item-content>
<v-list-item-title>{{ item.title }}</v-list-item-title>
<v-list-item-subtitle>{{ item.institution }} </v-list-item-subtitle>
</v-list-item-content>
</v-list-item>
An here is js function:
methods: {
handleChanging() {
if (this.selectAll === true) {
//here I want to check all checkboxes
} else {
//here to uncheck all
}
}
}
CodePudding user response:
You can do using this:
handleChanging() {
if (this.selectAll === true) {
this.itemsEducators.forEach(x => x.checked = true);
} else {
this.itemsEducators.forEach(x => x.checked = false);
}
}
CodePudding user response:
Try like following :
new Vue({
el: '#demo',
data() {
return {
itemsEducators: [
{title: 'title 1', checked: false, institution: '1'},
{title: 'title 2', checked: false, institution: '1'},
{title: 'title 3', checked: true, institution: '1'},
{title: 'title 4', checked: false, institution: '1'},
],
all: false
}
},
methods: {
handleChanging() {
this.itemsEducators = this.itemsEducators.map(i => {
i.checked = this.all
return i
})
},
setCheck() {
this.itemsEducators.find(c => c.checked === false) ? this.all = false : this.all = true
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<p>All</p>
<input type="checkbox" style="padding-right:15px; margin-bottom: 2em;" v-model="all" @change="handleChanging" />
<ul style="display: flex; list-style: none;">
<li v-for="(item, index) in itemsEducators" :key="index" style="margin-right: 2em;">
<input type="checkbox" :key="item.title" v-model="item.checked" @change="setCheck" />
<p>{{ item.title }}</p>
<li>
</ul>
</div>