模态框(弹出层对话框,Modal Popup)在大多数现代应用程序中非常常见。它们主要用于呈现简洁的信息,非常适合显示广告和促销内容。模态框提供了一种快速传达信息的方式,并提供了用户友好的关闭选项。
在本文中,我们将使用Vuejs构建一个弹出模态框。该模态框将包括一个取消或关闭按钮,以方便用户在完成任务后关闭它。此外,我们还将实现一个功能,允许用户在模态框区域外点击以关闭它。
<script setup lang="ts">
import { ref } from 'vue';
const message = ref('This is a modal popup');
const emit = defineEmits(['close']);
const closeModal = () => {
emit('close');
};
</script>
<template>
<div class="popup" @click.self="closeModal">
<div class="popup-content">
<div class="popup-header">
<h2 class="popup-title">{{ message }}</h2>
<button class="popup-close-button" @click.prevent="closeModal">X</button>
</div>
<article>
<div class="popup-content-text">
This is a simple modal popup in Vue.js
</div>
</article>
</div>
</div>
</template>
Script Section
<script setup lang="ts">
import { ref } from 'vue';
const message = ref('This is a modal popup');
const emit = defineEmits(['close']);
const closeModal = () => {
emit('close');
};
</script>
在这个部分,我们从Vue中导入所需的功能。
Template Section
<template>
<div class="popup" @click.self="closeModal">
<div class="popup-content">
<div class="popup-header">
<h2 class="popup-title">{{ message }}</h2>
<button class="popup-close-button" @click.prevent="closeModal">X</button>
</div>
<article>
<div class="popup-content-text">
This is a simple modal popup in Vue.js
</div>
</article>
</div>
</div>
</template>
本段代码义了模板中模态框的结构。
<script setup lang="ts">
import { ref } from 'vue'
import Popup from "@/components/Popup.vue"; // @ is an alias to /src
const msg = ref('Hello World!')
const isOpened = ref(false)
</script>
<template>
<div>
<h1>{{ msg }}</h1>
<button @click="isOpened = !isOpened">Open Popup</button>
<Teleport to="body">
<Popup v-if="isOpened" @close="isOpened = !isOpened" />
</Teleport>
</div>
</template>
数据和状态管理:
代码使用Vue的ref函数创建了两个响应式变量:
按钮点击事件
模板中有一个带有点击事件监听器(@click)的<button>元素。当按钮被点击时,它会切换isOpened变量的值,从而有效地打开或关闭弹出窗口。
导入弹出框组件
组件之间的通信:
您可以在CodeSandbox上使用本文中设计的代码进行在线体验。
https://codesandbox.io/s/suspicious-kepler-993dmh?file=%2Fsrc%2Fviews%2FHome.vue%3A0-420