Currently, I am developing a menu permission project using vue.js. Within this project, I have various submenus that are children of different menus. My objective is to automatically select all submenus under a selected menu when the user clicks on "select All". You can view the code implementation I am experimenting with here.
// Setting up a new VueJS instance
var app = new Vue({
el: "#app",
data: {
menus: [
{ id: 1, menuName: "Tech 1" },
{ id: 2, menuName: "Tech 2" },
{ id: 3, menuName: "Tech 3" }
],
selectedAllSubMenu:[],
selectedMenu: [],
selectedSubMenu: [],
submenus: [
{ id: 1, menuId: 1, subMenuName: "architecture" },
{ id: 2, menuId: 1, subMenuName: "Electrical" },
{ id: 3, menuId: 1, subMenuName: "Electronics" },
{ id: 4, menuId: 2, subMenuName: "IEM" },
{ id: 5, menuId: 3, subMenuName: "CIVIL" }
]
},
computed: {
isUserInPreviousUsers() {
return this.previousUsers.indexOf(this.userId) >= 0;
},
filteredProduct: function () {
const app = this,
menu = app.selectedMenu;
if (menu.includes("0")) {
return app.submenus;
} else {
return app.submenus.filter(function (item) {
return menu.indexOf(item.menuId) >= 0;
});
}
}
},
methods: {
selectAllSubMenu(event) {
for (let i = 0; i < this.submenus.length; i++) {
if (event.target.checked) {
if (this.submenus[i].menuId == event.target.value) {
this.selectedSubMenu.push(this.submenus[i].id);
}
} else {
if (this.submenus[i].menuId == event.target.value) {
var index = this.selectedSubMenu.indexOf(event.target.value);
this.selectedSubMenu.splice(index, 1);
}
}
}
},
}
});
<!-- Adding the library to the page -->
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5422213114667a667a6479363120357a65">[email protected]</a>/dist/vue.js"></script>
<!-- App -->
<div id="app">
<h4>By clicking on any menu, you can expand its submenus. To select all submenus of the chosen menu, click on "select All"</h4>
<table class="table">
<thead>
<tr>
<th>Menu</th>
<th>Submenu</th>
</tr>
</thead>
<tbody>
<tr v-for="(menu,index) in menus" :key="menu.id">
<td>
<label>
<input type="checkbox" :value="menu.id" v-model="selectedMenu" />{{ menu.menuName }}
</label>
</td>
<td v-if="selectedMenu.length != 0">
<ul>
<label >
<input
type="checkbox"
:value="menu.id"
v-model="selectedAllSubMenu"
@change="selectAllSubMenu"
/>
Select all
</label>
<li v-for="submenu in filteredProduct" :key="submenu.id" v-if="menu.id == submenu.menuId">
<input type="checkbox" :value="submenu.id" v-model="selectedSubMenu" />
<label>{{ submenu.subMenuName }} </label>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
As part of my project, each menu contains specific submenus. When a submenu is selected and then "select all" is clicked, all the submenus get selected. However, an issue arises when "select all" is unchecked as previously selected submenus remain selected. How can I address this challenge?