Reputation: 520
I have an Array of checkbox which already divided in to groups and I need to check all child checkbox if parent is checked and uncheck if parent is uncheck and then update all their state in Array. This wayyy over my head since I'm realy new to Vue.
I setup a Codepen here, and I can't change Array's structure since it's a JSON response from server.
Js
let tree = [
{
"text": "AccountController",
"id": 1,
"state": {
"opened": false,
"selected": true,
"disabled": false
},
"children": [
{
"text": "Index",
"id": 2,
"state": {
"opened": false,
"selected": true,
"disabled": false
},
"children": null
},
{
"text": "Login",
"id": 3,
"state": {
"opened": false,
"selected": true,
"disabled": false
},
"children": null
},
...
]
},
{
"text": "BaseController",
"id": 19,
"state": {
"opened": false,
"selected": true,
"disabled": false
},
"children": [
{
"text": "GetErrorListFromModelState",
"id": 20,
"state": {
"opened": false,
"selected": true,
"disabled": false
},
"children": null
},
{
"text": "GetErrorFromModelState",
"id": 21,
"state": {
"opened": false,
"selected": true,
"disabled": false
},
"children": null
},
...
]
}
]
let app = new Vue({
el : '#clone',
data : {
items : tree,
},
methods : {
submitForm() {
console.log(tree);
}
}
});
Html
<div id="clone">
<button @click="submitForm">click</button>
<div class="dd">
<ol class="dd-list">
<li v-for="(item, index) in items"
v-bind:class="[item.state.opened ? 'dd-item open' : 'dd-item']">
<div class="dd-handle"
@click="item.state.opened = !item.state.opened">
<input type="checkbox"
:disabled="item.state.disabled"
:name="item.text"
:checked="item.state.selected"
@click="item.state.selected = !item.state.selected">
<label :for="item.text">{{item.text}}</label>
</div>
<ol v-if="item.children.length != 0" class="dd-list">
<li v-for="(children, index) in item.children"
:data-id="children.id" class="dd-item">
<div class="dd-handle">
<input type="checkbox"
:name="children.text"
:checked="children.state.selected"
:disabled="children.state.disabled"
@click="children.state.selected = !children.state.selected">
<label :for="children.text">{{children.text}}</label>
</div>
</li>
</ol>
</li>
</ol>
</div>
</div>
Can someone enlighten me please. Thank in advance!
Upvotes: 2
Views: 9524
Reputation: 82439
In the template,
<input type="checkbox"
:disabled="item.state.disabled"
:name="item.text"
:checked="item.state.selected"
@click="item.state.selected = !item.state.selected"
@change="onChange(item, item.state.selected)">
And add the method,
methods : {
submitForm() {
console.log(tree);
},
onChange(item, state){
for(let child of item.children){
child.state.selected = state
}
}
}
Updated pen.
Upvotes: 3