Vue js 如何在菜单外单击时关闭引导下拉菜单
Posted
技术标签:
【中文标题】Vue js 如何在菜单外单击时关闭引导下拉菜单【英文标题】:Vue js How to close the bootstrap dropdown menu when clicked outside the menu 【发布时间】:2021-03-28 09:05:27 【问题描述】:当用户在下拉菜单之外点击时,我正在尝试关闭下拉菜单
header_component.vue
<div class="dropdown d-inline-block">
<a href="#" class="logo logo-dark">
<a href="javascript:void(0);" class="Logo-plus" @click="toggleMainMenu()">+</a>
<span class="logo-lg">
<img src="" id="topnav_heading_image">
</span>
</a>
<div class="dropdown-menu dropdown-menu-right" style="left: 0;right: auto;" v-bind:class="show_main_menu ? 'd-block' : ''">
..............
</div>
</div
到目前为止,我尝试的是在单击时将 addeventlistener 添加到正文并在关闭时将事件 removeEventListener 添加。 身体事件未触发。如何在 body onclick 中添加事件?
methods:
toggleMainMenu()
this.show_main_menu = !this.show_main_menu;
this.show_sub_menu = false;
this.setBodyClass();
,
openSubMenu(menu_key)
let formData = new FormData();
formData.append("access_token", window.settings.access_token);
formData.append('menu_key',menu_key);
this.show_main_menu = false;
axios.post('/api/get_sub_menus', formData).then((response) =>
if(response.is_sub_menu == 0)
window.location.href = response.route;
else
this.sub_menus = _.chunk(_.toArray(response.data.sub_menu), 3);
this.show_sub_menu = true;
);
,
setBodyClass()
var body = document.body;
body.classList.toggle('open');
if(this.show_main_menu)
body.addEventListener('click', e =>
this.toggleMainMenu;
);
else
body.removeEventListener('click', e =>
console.log('closed');
);
,
directives:
"my-directive":
bind: function(el, binding)
alert('hello');
this.el.addEventListener('click', e =>
this.toggleMainMenu;
);
,
unbind: function(el)
// Remove Event Listener
this.el.removeEventListener('click', e =>
console.log('closed');
);
我也尝试了指令,但它不起作用
<body class="container-fluid p-0" v-my-directive="1">\
<body
【问题讨论】:
Bootstrap 下拉菜单似乎已经具有该功能,它不起作用吗?顺便说一句<"/div>
有问题
错字我已更正。但问题没有解决。不,它不起作用
嗯,嵌套链接不是无效吗?!
请帮助我厌倦了所有方法
我找到了解决方案***.com/questions/46038989/…
【参考方案1】:
下面的代码解决了我的问题
mounted()
document.addEventListener('click', this.close);
,
methods:
toggleMainMenu()
this.show_main_menu = !this.show_main_menu;
this.show_sub_menu = false;
,
openSubMenu(menu_key)
let formData = new FormData();
formData.append("access_token", window.settings.access_token);
formData.append('menu_key',menu_key);
this.show_main_menu = false;
axios.post('/api/get_sub_menus', formData).then((response) =>
if(response.is_sub_menu == 0)
window.location.href = response.route;
else
this.sub_menus = _.chunk(_.toArray(response.data.sub_menu), 3);
this.show_sub_menu = true;
);
,
close (e)
if (!this.$el.contains(e.target))
this.show_main_menu = false;
,
beforeDestroy ()
document.removeEventListener('click',this.close);
,
【讨论】:
以上是关于Vue js 如何在菜单外单击时关闭引导下拉菜单的主要内容,如果未能解决你的问题,请参考以下文章