秀网站模板,西点培训前十名学校,网站定制怎么选择,纪检网站建设在 Vue 3 中#xff0c;如果你想判断点击的目标是否在弹框内#xff0c;可以通过以下步骤实现。这里我们将使用 ref 来引用弹框组件#xff0c;并在点击事件中进行判断。
示例代码
1. 创建弹框子组件
首先#xff0c;创建一个名为 Modal.vue 的子组件。
!-- Modal.vue …在 Vue 3 中如果你想判断点击的目标是否在弹框内可以通过以下步骤实现。这里我们将使用 ref 来引用弹框组件并在点击事件中进行判断。
示例代码
1. 创建弹框子组件
首先创建一个名为 Modal.vue 的子组件。
!-- Modal.vue --
templatediv classmodal refmodalRefdiv classmodal-contenth2{{ title }}/h2p{{ content }}/pbutton clickcloseModal关闭/button/div/div
/templatescript langts
import { defineComponent, PropType, ref } from vue;export default defineComponent({name: Modal,props: {title: {type: String as PropTypestring,required: true,},content: {type: String as PropTypestring,required: true,},},setup(props, { emit }) {const modalRef refHTMLElement | null(null);const closeModal () {emit(close);};return {modalRef,closeModal,};},
});
/scriptstyle scoped
.modal {position: absolute; /* 使弹窗不覆盖整个页面 */top: 50%; /* 垂直居中 */left: 50%; /* 水平居中 */transform: translate(-50%, -50%); /* 使其真正居中 */background: white;padding: 20px;border-radius: 5px;box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);z-index: 1000; /* 确保弹窗在其他元素之上 */
}
/style2. 在父组件中使用弹框
接下来在父组件中使用这个弹框组件并添加点击事件处理程序。
!-- ParentComponent.vue --
templatediv clickhandleClickbutton click.stopshowModal true打开弹窗/buttonModalv-ifshowModaltitle弹窗标题content这是弹窗的内容。closeshowModal falserefpopup//div
/templatescript langts
import { defineComponent, ref } from vue;
import Modal from ./Modal.vue; // 确保路径正确export default defineComponent({components: {Modal,},setup() {const showModal ref(false);const popup refInstanceTypetypeof Modal | null(null);const handleClick (event: MouseEvent) {const target event.target as HTMLElement;if (popup.value !popup.value.$el.contains(target)) {showModal.value false; // 点击弹框外部区域时关闭弹框}};return {showModal,handleClick,popup,};},
});
/script解释Modal.vue:
这是弹框的子组件接收 title 和 content 作为 props。使用 ref 来引用弹框的 DOM 元素。ParentComponent.vue:
在父组件中使用 click 事件监听整个组件的点击事件。在 handleClick 方法中使用 popup.value.$el.contains(target) 来判断点击的目标是否在弹框内。如果不在则关闭弹框。使用 click.stop 来阻止点击按钮时触发父组件的点击事件。总结
通过这种方式你可以使用 popup.$el.contains(target) 来判断点击的目标是否在弹框内从而实现点击弹框外部区域关闭弹框的功能。这种方法可以确保代码的清晰性和可维护性。