0👍
So Apparently, the key to ‘modeling’ complex structures as this is avoiding ‘v-model’; as v-model is syntax sugar for 2 separate props (which vary by input)
for checkboxes, its sugar for checked
and @change,
for text input it’s value and @input
, etc.
This response however is somewhat tailored to the raised issue and is courtesy of guanzo. As opposed to using v-model for the modeling or binding in this case. Functions were used to achieve this.
isPermissionChecked(pName) {
return this.selected.some((p) => p.name === pName);
},
togglePermission(pName, event) {
const isChecked = event.target.checked;
if (isChecked) {
this.selected.push({ name: pName, sub_permissions: [] });
} else {
const i = this.selected.findIndex((p) => p.name === pName);
this.selected.splice(i, 1);
}
},
isSubPermissionChecked(pName, spName) {
const permission = this.selected.find((p) => p.name === pName);
return (
permission && permission.sub_permissions.some((sp) => sp === spName)
);
},
toggleSubPermission(pName, spName, event) {
const isChecked = event.target.checked;
const permission = this.selected.find((p) => p.name === pName);
if (isChecked) {
permission.sub_permissions.push(spName);
} else {
const i = permission.sub_permissions.findIndex((sp) => sp === spName);
permission.sub_permissions.splice(i, 1);
}
},
These were ‘modelled’ to the inputs like so:
<div v-for="p in permissions" :key="p.name" class="card">
<div class="form-grop d-flex align-items-center radio-group1">
<div class="mr-auto">
<input
type="checkbox"
:id="p.name"
:checked="isPermissionChecked(p.name)"
@change="togglePermission(p.name, $event)"
class="mt-2"
/>
<label :for="p.name" class="mx-2 mt-2">{{ p.name }}</label>
</div>
<div>
</div>
and
<div class="mr-auto" v-for="sp in p.sub_permissions" :key="sp">
<input
type="checkbox"
:id="p.name + sp"
:disabled="!isPermissionChecked(p.name)"
:checked="isSubPermissionChecked(p.name, sp)"
@change="toggleSubPermission(p.name, sp, $event)"
class="mt-2"
/>
<label :for="p.name + sp" class="mx-2 mt-2">{{ sp }}</label>
</div>
Source:stackexchange.com