详细报错为:
Uncaught TypeError: sidebar.value.contains is not a function at HTMLDocument.checkIfOutsideClick (header.vue:134:39)
点击除你这个元素外的任何地方,未能将元素隐藏的BUG
原来代码:
const sidebar = ref(null); // 使用 ref 创建一个引用
const closeSidebarOnClickOutside = (event) => {
// 点击事件发生在侧边栏之外时,关闭侧边栏
if (sidebar.value && !sidebar.value.contains(event.target)) {
showSidebar.value = false;
}
};
onMounted(() => {
// 在组件挂载后,监听整个页面的点击事件
document.addEventListener("click", closeSidebarOnClickOutside);
});
onBeforeUnmount(() => {
// 在组件销毁前,移除点击事件监听器
document.removeEventListener("click", closeSidebarOnClickOutside);
});
其实换种方法,用js原生获取dom类型的方法就可以了
改为:
let sidebarElement; // Variable to hold the sidebar DOM element
const checkIfOutsideClick = (event) => {
// Check if the click was outside the sidebar element
if (sidebarElement && !sidebarElement.contains(event.target)) {
showSidebar.value = false; // Close the sidebar if click is outside
}
};
onMounted(() => {
// Select the sidebar element using its class or id
sidebarElement = document.querySelector('.sidebar_'); // Adjust the selector as needed
// Listen for clicks on the entire document
document.addEventListener('click', checkIfOutsideClick, true);
});
onBeforeUnmount(() => {
// Remove the event listener when the component is unmounted
document.removeEventListener('click', checkIfOutsideClick, true);
});