I want to make an Accordion menu in vuejs. The Accordion should not close if another div is clicked. It should close when the Accordion item itself is clicked. How do I achieve this?
vue code
new Vue({
el: '#demo',
data () {
return {
isOpen: false,
selected: '',
headerDesktopMenu: {
menu: {
menu_items: [{item_name:11111, childrens: [{item_name: 11}, {item_name: 12}]},{item_name:22222, childrens: [{item_name: 21}, {item_name: 22}]},{item_name:33333, childrens: [{item_name: 31}, {item_name: 32}]},{item_name:44444, childrens: [{item_name: 41}, {item_name: 42}]}]
}
}
}
},
methods: {
toggleAccordion (item) {
item == this.selected ? this.isOpen = !this.isOpen : this.isOpen = true
this.selected = item
}
},
computed: {
accordionClasses () {
return {
'is-closed': !this.isOpen,
'is-primary': this.isOpen,
'is-dark': !this.isOpen
};
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
HTML code
<div id="demo">
<ul v-if="headerDesktopMenu.menu.menu_items">
<li v-for="(menu, index) in headerDesktopMenu.menu.menu_items" :key="index" : v-if="headerDesktopMenu.menu.menu_items">
<a @click="toggleAccordion(menu.item_name)">{{ menu.item_name }}</a>
<ul v-if="menu.childrens">
<li v-for="(submenuone, indexone) in menu.childrens" :key="indexone" v-if="isOpen && menu.item_name === selected">
<a >{{ submenuone.item_name }}</a>
</li>
</ul>
</li>
CodePudding user response:
I think you need to keep a list of which top level menu items to display or not display. Something like this.
https://codesandbox.io/s/jovial-carson-n2exv?file=/src/App.vue
<template>
<div id="app">
<ul v-if="headerDesktopMenu.menu.menu_items">
<li
v-for="(menu, index) in headerDesktopMenu.menu.menu_items"
:key="index"
:
>
<a @click="toggleAccordion(menu.item_name)">{{
menu.item_name
}}</a>
<ul
v-if="menu.childrens && displayArray[menu.item_name]"
>
<li
v-for="(submenuone, indexone) in menu.childrens"
:key="indexone"
>
<a >{{ submenuone.item_name }}</a>
</li>
</ul>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "App",
components: {},
data() {
return {
isOpen: false,
selected: "",
displayArray: {},
headerDesktopMenu: {
menu: {
menu_items: [
{
item_name: 11111,
childrens: [{ item_name: 11 }, { item_name: 12 }],
},
{
item_name: 22222,
childrens: [{ item_name: 21 }, { item_name: 22 }],
},
{
item_name: 33333,
childrens: [{ item_name: 31 }, { item_name: 32 }],
},
{
item_name: 44444,
childrens: [{ item_name: 41 }, { item_name: 42 }],
},
],
},
},
};
},
methods: {
toggleAccordion(item) {
if (this.displayArray[item] === undefined) {
this.$set(this.displayArray, item, true);
} else {
this.$set(this.displayArray, item, !this.displayArray[item]);
}
},
},
computed: {
accordionClasses() {
return {
"is-closed": !this.isOpen,
"is-primary": this.isOpen,
"is-dark": !this.isOpen,
};
},
},
};
</script>