# 09. Modal 弹窗
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/03.%20%E7%BB%84%E4%BB%B6%E5%BA%93%E6%96%87%E6%A1%A3/05.%20%E5%BC%B9%E7%AA%97%E7%BB%84%E4%BB%B6/09.%20Modal%20%E5%BC%B9%E7%AA%97

JModal 弹窗组件使用指南


# JModal 弹窗组件

> [!info] 基于 Ant Design Vue Modal 封装的弹窗组件，支持全屏、自定义高度、拖拽等功能。

## 组件路径

- **组件文件**: `@/components/Modal/src/JModal/JModal.vue`
- **类型定义**: `@/components/Modal/src/typing.ts`
- **Props 定义**: `@/components/Modal/src/props.ts`
- **Hooks**: `@/components/Modal/src/hooks/useModal.ts`

## 基本用法

### 简单弹窗

```vue
<template>
  <div>
    <a-button type="primary" @click="visible = true">打开弹窗</a-button>
    <JModal
      v-model:open="visible"
      title="基本弹窗"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p>这是一段弹窗内容...</p>
    </JModal>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const visible = ref(false);

function handleOk() {
  console.log('确认操作');
  visible.value = false;
}

function handleCancel() {
  console.log('取消操作');
  visible.value = false;
}
</script>
```

### 使用 Hooks 控制

```vue
<template>
  <div>
    <a-button type="primary" @click="openModal">打开弹窗</a-button>
    <JModal @register="register" title="Hooks 控制弹窗" />
  </div>
</template>

<script setup lang="ts">
import { useModal } from '@/components/Modal';

const [register, { openModal, closeModal, setModalProps }] = useModal();

// 打开弹窗并传递数据
function openWithData() {
  openModal(true, { id: 1, name: '测试数据' });
}

// 动态设置属性
function updateProps() {
  setModalProps({
    width: 1000,
    title: '新标题',
    fullscreen: true,
  });
}
</script>
```

## Props 属性

### 基础属性

| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| visible / open | `boolean` | `false` | 是否显示弹窗（推荐使用 `v-model:open`） |
| title | `string` | - | 弹窗标题 |
| width | `string \| number` | `520` | 弹窗宽度 |
| height | `number` | - | 弹窗高度 |
| minHeight | `number` | `500` | 最小高度 |
| maxHeight | `number` | `600` | 最大高度（控制 bodyStyle） |
| centered | `boolean` | `false` | 是否垂直居中 |
| fullscreen | `boolean` | `false` | 是否全屏显示 |
| defaultFullscreen | `boolean` | `false` | 默认全屏 |
| canFullscreen | `boolean` | `true` | 是否可全屏 |
| draggable | `boolean` | `true` | 是否可拖拽 |

### 按钮属性

| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| okText | `string` | `'确定'` | 确认按钮文字 |
| cancelText | `string` | `'取消'` | 取消按钮文字 |
| okType | `string` | `'primary'` | 确认按钮类型 |
| showOkBtn | `boolean` | `true` | 是否显示确认按钮 |
| showCancelBtn | `boolean` | `true` | 是否显示取消按钮 |
| confirmLoading | `boolean` | `false` | 确认按钮加载状态 |
| okButtonProps | `ButtonProps` | - | 确认按钮属性 |
| cancelButtonProps | `ButtonProps` | - | 取消按钮属性 |

### 交互属性

| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| maskClosable | `boolean` | `true` | 点击蒙层是否关闭 |
| mask | `boolean` | `true` | 是否显示蒙层 |
| maskStyle | `CSSProperties` | - | 蒙层样式 |
| keyboard | `boolean` | `true` | 是否支持 ESC 键关闭 |
| closable | `boolean` | `true` | 是否显示关闭按钮 |
| closeIcon | `VNodeChild` | - | 自定义关闭图标 |
| closeFunc | `() => Promise<boolean>` | - | 自定义关闭逻辑（返回 true 允许关闭） |
| destroyOnClose | `boolean` | `false` | 关闭时销毁内容 |
| getContainer | `() => HTMLElement` | - | 指定弹窗挂载容器 |

### 样式属性

| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| bodyStyle | `CSSProperties` | - | 内容区域样式 |
| wrapClassName | `string` | - | 容器自定义类名 |
| zIndex | `number` | `1000` | 弹窗 z-index |

### 功能属性

| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| loading | `boolean` | `false` | 加载状态 |
| loadingTip | `string` | - | 加载提示文字 |
| useWrapper | `boolean` | `true` | 是否使用包装器 |
| wrapperFooterOffset | `number` | `0` | 底部偏移量 |
| wrapperProps | `ModalWrapperProps` | - | 包装器属性 |
| helpMessage | `string \| string[]` | - | 帮助信息（显示在标题旁） |
| enableComment | `boolean` | `false` | 是否开启评论区域 |
| afterClose | `() => void` | - | 关闭后的回调 |
| footer | `VNodeChild` | - | 自定义底部内容 |

## Emits 事件

| 事件名 | 参数 | 说明 |
|--------|------|------|
| ok | `e: Event` | 点击确认按钮时触发 |
| cancel | `e: Event` | 点击取消按钮时触发 |
| register | `methods: ModalMethods, uid: string` | 组件注册时触发（用于 Hooks） |
| open-change | `visible: boolean` | 弹窗显示状态变化时触发 |
| update:open | `visible: boolean` | 更新弹窗显示状态（v-model） |
| fullScreen | - | 全屏状态变化时触发 |

## useModal Hooks

### useModal（外部调用）

用于在父组件中控制弹窗：

```typescript
import { useModal } from '@/components/Modal';

const [register, methods] = useModal();
```

**返回方法：**

| 方法 | 参数 | 说明 |
|------|------|------|
| register | `(methods: ModalMethods, uuid: string) => void` | 注册弹窗实例 |
| openModal | `<T>(visible?: boolean, data?: T, openOnSet?: boolean) => void` | 打开弹窗并传递数据 |
| closeModal | `() => void` | 关闭弹窗 |
| setModalProps | `(props: Partial<ModalProps>) => void` | 动态设置弹窗属性 |
| getVisible | `ComputedRef<boolean>` | 获取显示状态（computed） |
| getOpen | `ComputedRef<boolean>` | 获取打开状态（computed） |
| redoModalHeight | `() => void` | 重新计算弹窗高度 |

### useModalInner（内部调用）

用于在弹窗内部组件中接收数据和操作：

```typescript
import { useModalInner } from '@/components/Modal';

const [register, methods] = useModalInner((data) => {
  // 接收外部传递的数据
  console.log('接收数据:', data);
});
```

**返回方法：**

| 方法 | 参数 | 说明 |
|------|------|------|
| register | `(methods: ModalMethods, uuid: string) => void` | 注册弹窗实例 |
| changeLoading | `(loading: boolean) => void` | 设置加载状态 |
| changeOkLoading | `(loading: boolean) => void` | 设置确认按钮加载状态 |
| closeModal | `() => void` | 关闭弹窗 |
| setModalProps | `(props: Partial<ModalProps>) => void` | 动态设置弹窗属性 |
| getVisible | `ComputedRef<boolean>` | 获取显示状态 |
| getOpen | `ComputedRef<boolean>` | 获取打开状态 |
| redoModalHeight | `() => void` | 重新计算弹窗高度 |

## 插槽 Slots

| 插槽名 | 说明 | 参数 |
|--------|------|------|
| default | 内容区域 | - |
| title | 标题区域 | - |
| footer | 底部区域 | - |
| closeIcon | 关闭图标 | - |

```vue
<JModal title="自定义弹窗">
  <template #title>
    <span>自定义标题</span>
    <a-tooltip title="帮助信息">
      <QuestionCircleOutlined />
    </a-tooltip>
  </template>

  <p>内容区域</p>

  <template #footer>
    <a-space>
      <a-button @click="handleCustom1">自定义按钮1</a-button>
      <a-button type="primary" @click="handleCustom2">自定义按钮2</a-button>
    </a-space>
  </template>
</JModal>
```

## 完整示例：表单弹窗

```vue
<template>
  <div>
    <a-button type="primary" @click="openUserModal">新建用户</a-button>

    <UserModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
import { useModal } from '@/components/Modal';
import UserModal from './UserModal.vue';

const [registerModal, { openModal }] = useModal();

function openUserModal() {
  openModal(true, {
    isEdit: false,
  });
}

function handleSuccess() {
  console.log('操作成功');
}
</script>
```

**UserModal.vue:**

```vue
<template>
  <JModal
    :visible="visible"
    :title="title"
    :width="600"
    :confirmLoading="loading"
    @ok="handleSubmit"
    @register="register"
  >
    <BasicForm @register="registerForm" />
  </JModal>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useForm, useModalInner } from '@/components/Form';
import { saveUser } from '@/api/system/user';

const emit = defineEmits(['success']);
const loading = ref(false);
const isEdit = ref(false);
const userId = ref('');

const title = computed(() => isEdit.value ? '编辑用户' : '新建用户');

const [registerForm, { getFieldsValue, validate, resetFields, setFieldsValue }] = useForm({
  schemas: [
    {
      field: 'username',
      label: '用户名',
      component: 'Input',
      required: true,
    },
    {
      field: 'email',
      label: '邮箱',
      component: 'Input',
      rules: [{ type: 'email', message: '邮箱格式不正确' }],
    },
  ],
  showActionButtonGroup: false,
});

const [register, { changeOkLoading, closeModal }] = useModalInner((data) => {
  resetFields();
  isEdit.value = data.isEdit;
  userId.value = data.id || '';

  if (isEdit.value) {
    setFieldsValue(data.record);
  }
});

async function handleSubmit() {
  try {
    const values = await validate();
    changeOkLoading(true);
    await saveUser({ ...values, id: userId.value });
    changeOkLoading(false);
    emit('success');
    closeModal();
  } catch (error) {
    changeOkLoading(false);
  }
}
</script>
```

## 注意事项

1. **推荐使用 `v-model:open`** 代替 `visible`，符合 Ant Design Vue 4.x 规范
2. **双击标题** 可以切换全屏（当 `fullscreen` 为 `true` 时）
3. **移动端** 会自动全屏显示
4. **closeFunc** 可以实现关闭前的确认逻辑，返回 `true` 允许关闭
5. **useModal** 数据传递通过内部 `dataTransfer` 实现，确保唯一性

## 相关链接

- [[01. Drawer 抽屉]]
- [[02. Popover 气泡卡片]]
- [[03. Tooltip 文字提示]]
