使用vue3+ts组合式api方式封装一个弹框组件
时间: 2025-06-15 16:21:27 浏览: 2
使用Vue3结合TypeScript (TS) 创建一个弹框组件通常会涉及到声明组件、处理props和事件以及管理状态。以下是使用Vue3的Composition API(组合API)来封装一个基础的弹框组件的步骤:
首先,在项目中安装`@vue/cli-plugin-typescript`并确保已启用TypeScript支持。
```bash
npm install @vue/cli-plugin-typescript --save-dev
```
1. 定义弹框组件的结构:
创建一个名为`Dialog.vue`的文件,并添加以下内容:
```typescript
<template>
<div class="dialog" v-if="show">
<slot></slot>
<button @click="close">关闭</button>
</div>
</template>
<script lang="ts">
import { Component, Prop, Ref } from 'vue';
interface DialogProps {
show: boolean;
}
export default class DialogComponent extends Component<DialogProps> {
// 弹窗显示的Ref实例
private dialogRef = ref(false);
// 显示和隐藏弹窗的方法
close() {
this.dialogRef.value = false;
}
// TypeScript 接口绑定prop值
show: DialogProps['show'] = false;
mounted() {
// 如果prop传入true,初始化显示
if (this.show) {
this.dialogRef.value = true;
}
}
}
</script>
<style scoped>
.dialog {
/* 样式省略 */
}
</style>
```
在这个例子中,我们使用了Vue3的Composition API来管理组件的状态(`dialogRef`),并通过`v-if`指令控制弹框的显示和隐藏。`DialogProps`接口定义了接收的prop类型,`show`属性则通过类型断言设置为prop类型。
2. 在父组件中使用这个组件:
```html
<template>
<div>
<!-- 父组件的内容 -->
<DialogComponent :show.sync="isShowingDialog" />
</div>
</template>
<script setup>
import DialogComponent from '@/components/Dialog.vue';
const isShowingDialog = ref(false);
</script>
```
当需要打开弹框时,可以设置`isShowingDialog`为`true`;关闭时,由父组件触发`close`方法。
阅读全文
相关推荐


















