我想用vejs制作一个Accordion菜单。如果单击另一个div, Accordion不应该关闭。当单击Accordion项本身时,它应该关闭。我该如何做到这一点?
vue代码
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
<div id="demo">
<ul class="level-0-wrp" v-if="headerDesktopMenu.menu.menu_items">
<li class="level-0" v-for="(menu, index) in headerDesktopMenu.menu.menu_items" :key="index" :class="accordionClasses" v-if="headerDesktopMenu.menu.menu_items">
<a class="title" @click="toggleAccordion(menu.item_name)">{{ menu.item_name }}</a>
<ul class="level-1-wrp" v-if="menu.childrens">
<li class="level-1" v-for="(submenuone, indexone) in menu.childrens" :key="indexone" v-if="isOpen && menu.item_name === selected">
<a class="title">{{ submenuone.item_name }}</a>
</li>
</ul>
</li>
我认为您需要保留一个列表,列出要显示或不显示的顶级菜单项。像这样。
https://codesandbox.io/s/jovial-carson-n2exv?file=/src/App.vue
<template>
<div id="app">
<ul class="level-0-wrp" v-if="headerDesktopMenu.menu.menu_items">
<li
class="level-0"
v-for="(menu, index) in headerDesktopMenu.menu.menu_items"
:key="index"
:class="accordionClasses"
>
<a class="title" @click="toggleAccordion(menu.item_name)">{{
menu.item_name
}}</a>
<ul
class="level-1-wrp"
v-if="menu.childrens && displayArray[menu.item_name]"
>
<li
class="level-1"
v-for="(submenuone, indexone) in menu.childrens"
:key="indexone"
>
<a class="title">{{ 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>