diff --git a/src/components/AccountMenu/AcctMenu.vue b/src/components/AccountMenu/AcctMenu.vue index cc03d90..5a363f5 100644 --- a/src/components/AccountMenu/AcctMenu.vue +++ b/src/components/AccountMenu/AcctMenu.vue @@ -59,7 +59,7 @@ * with links to account management, my account, and logout. */ -import { computed, onMounted, ref } from "vue"; +import { computed, onMounted, onBeforeUnmount, ref } from "vue"; import { storeToRefs } from "pinia"; import i18next from "@/i18n/i18n"; import { useRouter, useRoute } from "vue-router"; @@ -106,21 +106,27 @@ const onBtnMyAccountClick = async () => { await router.push("/my-account"); }; -/** Registers a click listener to close the menu when clicking outside. */ -const clickOtherPlacesThenCloseMenu = () => { +/** + * Closes the menu when clicking outside. Stored as a named + * function so it can be removed in onBeforeUnmount. + * @param {MouseEvent} event - The click event. + */ +const handleDocumentClick = (event) => { const acctMgmtButton = document.getElementById("acct_mgmt_button"); const acctMgmtMenu = document.getElementById("account_menu"); + if ( + acctMgmtMenu && + acctMgmtButton && + !acctMgmtMenu.contains(event.target) && + !acctMgmtButton.contains(event.target) + ) { + acctMgmtStore.closeAcctMenu(); + } +}; - document.addEventListener("click", (event) => { - if ( - acctMgmtMenu && - acctMgmtButton && - !acctMgmtMenu.contains(event.target) && - !acctMgmtButton.contains(event.target) - ) { - acctMgmtStore.closeAcctMenu(); - } - }); +/** Registers a click listener to close the menu when clicking outside. */ +const clickOtherPlacesThenCloseMenu = () => { + document.addEventListener("click", handleDocumentClick); }; /** Navigates to the Account Admin page. */ @@ -161,6 +167,10 @@ onMounted(async () => { await getIsAdminValue(); clickOtherPlacesThenCloseMenu(); }); + +onBeforeUnmount(() => { + document.removeEventListener("click", handleDocumentClick); +});