单击任意位置时如何关闭下拉列表
Posted
技术标签:
【中文标题】单击任意位置时如何关闭下拉列表【英文标题】:How to close a dropdown list when clicking anywhere 【发布时间】:2021-01-14 22:35:14 【问题描述】:如何关闭单击任意位置时打开的下拉菜单?
这段代码:
<tr class="inputs-table">
<td>Type object: </td>
<td>
<div class="select">
<div class="select-header form-control" v-on:click="AddForm(1)">
<span class="select__current">Please select one option</span>
</div>
<addForm v-if="addedForm === 1" />
</div>
</td>
</tr>
<tr class="inputs-table">
<td>Type business-model: </td>
<td>
<div class="select">
<div class="select-header form-control" v-on:click="AddForm(2)">
<span class="select__current">Please select one option</span>
</div>
<addForm v-if="addedForm === 2" />
</div>
</td>
</tr>
export default
name: 'Index',
data()
return
addedForm: 0,
,
methods:
AddForm(number)
this.addedForm = number;
,
closeForm()
this.addedForm = false;
,
components:
addForm,
下拉列表:
接下来我可以尝试什么?
【问题讨论】:
这能回答你的问题吗? how to hide dropdown menu if we click outside the menu in vuejs 试试这个,<div class="select-header form-control" v-on:click="AddForm(1)" v-on:blur="closeForm()">
【参考方案1】:
您可以使用 if window.onClick
并查看它是否与您的元素匹配。如果没有,则关闭它;调用检查mounted和beforeDestroy或breforeRouteLeave点击的函数。
例如:
mounted()
this.hideNav()
,
methods:
hideNav()
window.onclick = function(event)
if (!event.target.matches('.select__body'))
this.closeForm()
,
beforeRouteLeave()
this.hideNav()
【讨论】:
@АртёмСтоляр 拍我的坏话。答案已更新,您需要先拥有this.
,然后才能调用hideNav
嘿,对不起,谢谢,但仍然无法正常工作并给出错误“this.closeForm is not a function at window.onclick”
也许你知道怎么回事
@АртёмСтоляр 将window.onclick = function(event)
替换为window.addEventListener("click", function(event)
看看是否有效
不,又报错“ TypeError: this.closeForm is not a function at eval”【参考方案2】:
<template>
<div
@click="dropdownIsActive = !dropdownIsActive"
ref="dropdown"
>
</div>
</template>
<script>
export default
data: () => (
dropdownIsActive: false
),
created ()
window.addEventListener('click', this.closeDropdown)
,
methods:
closeDropdown (e)
if (!this.$refs.dropdown.contains(e.target))
this.dropdownIsActive = false
,
beforeDestroy ()
window.removeEventListener('click', this.closeDropdown)
</script>
【讨论】:
以上是关于单击任意位置时如何关闭下拉列表的主要内容,如果未能解决你的问题,请参考以下文章