[英]What makes this dropdown menu hide when you click outside of the menu?
[英]how to hide dropdown menu if we click outside the menu in vuejs
我在 vuejs 中使用dropdown
菜單組件來制作普通的下拉菜單。 我的dropdown
組件代碼是:
<template>
<span class="dropdown" :class="{shown: state}">
<a href="#" @click.prevent="toggleDropdown" class="dropdown-toggle">toggle menu</a>
<div class="dropdown-menu" v-show="state">
<ul class="list-unstyled">
<slot></slot>
</ul>
</div>
</transition>
</span>
</template>
<script>
export default {
name: 'dropdown',
data () {
return {
state: false
}
},
methods: {
toggleDropdown (e) {
this.state = !this.state;
}
}
}
</script>
現在我通過在模板中使用以下代碼在我的VUE
應用程序中的不同位置導入dropdown
組件
<dropdown>
<li>
Action
</li>
</dropdown>
現在工作正常,但我希望同時只有一個下拉菜單處於活動狀態。
我做了很少的研究,發現我可以使用像https://github.com/davidnotplay/vue-my-dropdown這樣的插件,但我不想使用它。 同樣,我還研究了上述示例的工作原理,但我想以這樣一種方式實現此下拉功能,即我的dropdown
組件將處理與下拉相關的所有事件。 那么你能幫我實現這個目標嗎?
看看vue-clickaway。( 鏈接 )
有時您需要檢測元素外部的點擊(以關閉模式窗口或隱藏下拉選擇)。 沒有本地事件,並且Vue.js也不涵蓋您。 這就是存在vue-clickaway的原因。 在進一步閱讀之前,請查看演示。
我知道這是一個很老的問題,但是我認為沒有任何外部插件的最佳方法是在安裝的生命周期掛鈎中添加一個Click偵聽器(並在beforeDestroy掛鈎上將其刪除)並過濾組件上的點擊,以便僅在以下情況下隱藏在外面點擊。
<template>
<span class="dropdown" :class="{shown: state}">
<a href="#" @click.prevent="toggleDropdown" class="dropdown-toggle">toggle menu</a>
<div class="dropdown-menu" v-show="state">
<ul class="list-unstyled">
<slot></slot>
</ul>
</div>
<transition/>
</span>
</template>
<script>
export default {
name: 'dropdown',
data () {
return {
state: false
}
},
methods: {
toggleDropdown (e) {
this.state = !this.state
},
close (e) {
if (!this.$el.contains(e.target)) {
this.state = false
}
}
},
mounted () {
document.addEventListener('click', this.close)
},
beforeDestroy () {
document.removeEventListener('click',this.close)
}
}
</script>
在 Vue 3 中,以下應該有效
請注意,下拉觸發器和下拉內容上的@click.stop
阻止文檔事件執行關閉功能。
<template>
<div class="dropdown" :class="{'is-active': dropdown.active.value}">
<div class="dropdown-trigger">
<button class="button" @click.stop="dropdown.active.value = !dropdown.active.value">
Toggle
</button>
</div>
<div class="dropdown-menu" role="filter">
<div class="dropdown-content" @click.stop>
<!-- dropdown items -->
</div>
</div>
</div>
</template>
<script>
import { defineComponent, ref, onMounted, onBeforeUnmount } from "vue";
export default defineComponent({
name: "Dropdown",
setup(){
const dropdown = {
active: ref(false),
close: () => {
dropdown.active.value = false
}
}
onBeforeUnmount(() => {
document.removeEventListener('click', dropdown.close)
})
onMounted(() => {
document.addEventListener('click', dropdown.close)
})
return {
dropdown
}
}
})
</script>
此示例使用bulma
但當然您不需要。
您可以利用blur
事件,例如,如果添加方法:
close() {
setTimeout(() => {
this.state = false;
}, 200);
}
並為您的鏈接設置blur
事件:
<a href="#" @click.prevent="toggleDropdown" @blur="close">toggle menu</a>
然后,每當您的切換鏈接失去焦點時,下拉列表都將被隱藏。 setTimeout
是必需的,因為Java單擊事件在模糊后發生,這將導致下拉鏈接不可單擊。 要變通解決此問題,延遲菜單隱藏一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.