需求:
- 封装一个弹窗组件(使用setup)
- 在父组件引用这个弹窗组件,父组件控制弹窗显示,弹窗内控制弹窗关闭。
步骤:
- 新建项目
npm init vite@latest
- 在src目录下components下创建组件Dialog文件夹,在该文件夹下创建Dialog.vue和Dialog.css
- 在App.vue(父组件)中引入Dialog组件
- 在App.vue中添加按钮控制Dialog组件的显示
代码:
父组件App.vue
<!--App.vue-->
<script setup lang="ts">
import { ref } from "vue";
import MyDialog from "./components/dialog/MyDialog.vue";
const dialogRef = ref(); // 获得组件引用
function open() {
dialogRef.value?.showdialog(); // 调用组件内部方法
}
</script>
<template>
<div style="position: relative">
<button @click="open">打开弹窗</button>
<MyDialog ref="dialogRef"></MyDialog>
</div>
</template>
<style scoped></style>
子组件MyDialog.vue
<!-- MyDialog.vue -->
<template>
<div class="dialog" draggable="true" v-show="isShowdialog">
<h1 class="title">这是一个弹窗</h1>
<div class="content">这是弹窗内容</div>
<div class="handler">
<button @click="hiddendialog">关闭弹窗</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, defineExpose } from "vue";
const isShowdialog = ref<boolean>(false);
function showdialog() {
isShowdialog.value = true;
}
function hiddendialog() {
isShowdialog.value = false;
}
defineExpose({ showdialog });
</script>
<style scoped>
@import url(./dialog.css);
</style>
子组件样式
/* dialog.css */
.dialog {
position: absolute;
top: 0px;
display: flex;
flex-direction: column;
margin: auto;
justify-content: center;
text-align: center;
background-color: rgb(192, 192, 192);
box-sizing: border-box;
width: 100%;
min-height: 800px;
border: 2px solid wheat;
z-index: 999;
}
vscode 可能出现的错误提示:编译问题
解决方案:tsconfig.app.json替换如下配置
,"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "src/**/**/*.vue"]
参考资料:
https://cn.vuejs.org/api/
demo源码地址:https://gitee.com/dminezjr/practice.git