# useMessage 消息提示 Hook
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/04.%20Hooks%E6%96%87%E6%A1%A3/01.%20WebHooks/useMessage


# useMessage 消息提示 Hook

## 概述

`useMessage` 提供全局消息提示、通知、模态框等功能，基于 Ant Design Vue 封装。

## 导入方式

```typescript
import { useMessage } from '@/hooks/web';
```

## 返回值

```typescript
interface UseMessageReturn {
  createMessage: MessageApi;           // 消息提示
  notification: NotifyApi;             // 通知提示
  createConfirm: (options) => void;    // 确认框
  createConfirmSync: (options) => Promise<boolean>;  // 同步确认框
  createSuccessModal: (options) => void;  // 成功模态框
  createErrorModal: (options) => void;     // 错误模态框
  createInfoModal: (options) => void;      // 信息模态框
  createWarningModal: (options) => void;   // 警告模态框
}
```

## API 详解

### 1. createMessage 消息提示

#### 类型定义

```typescript
interface MessageApi {
  success(content: string, duration?: number): void;
  error(content: string, duration?: number): void;
  info(content: string, duration?: number): void;
  warning(content: string, duration?: number): void;
  warn(content: string, duration?: number): void;
  loading(content: string, duration?: number): void;
  config(options: ConfigProps): void;
  destroy(): void;
}
```

#### 使用示例

```vue
<script setup lang="ts">
import { useMessage } from '@/hooks/web';

const { createMessage } = useMessage();

// 成功消息
const showSuccess = () => {
  createMessage.success('操作成功');
};

// 错误消息
const showError = () => {
  createMessage.error('操作失败');
};

// 信息消息
const showInfo = () => {
  createMessage.info('这是一条提示');
};

// 警告消息
const showWarning = () => {
  createMessage.warning('请注意');
};

// 加载消息
const showLoading = () => {
  const hide = createMessage.loading('加载中...');
  setTimeout(() => hide(), 2000);
};
</script>
```

### 2. notification 通知提示

#### 类型定义

```typescript
interface NotifyApi {
  success(config: NotificationArgsProps): void;
  error(config: NotificationArgsProps): void;
  info(config: NotificationArgsProps): void;
  warn(config: NotificationArgsProps): void;
  warning(config: NotificationArgsProps): void;
  open(args: NotificationArgsProps): void;
  close(key: String): void;
  config(options: ConfigProps): void;
  destroy(): void;
}
```

#### 使用示例

```vue
<script setup lang="ts">
import { useMessage } from '@/hooks/web';

const { notification } = useMessage();

// 成功通知
const showSuccessNotify = () => {
  notification.success({
    message: '通知标题',
    description: '这是一条成功通知',
    duration: 3,
  });
};

// 错误通知
const showErrorNotify = () => {
  notification.error({
    message: '错误',
    description: '操作失败，请重试',
  });
};

// 信息通知
const showInfoNotify = () => {
  notification.info({
    message: '系统消息',
    description: '您有新的消息',
    placement: 'topRight',
  });
};
</script>
```

### 3. createConfirm 确认框

#### 类型定义

```typescript
interface ModalOptionsEx {
  iconType?: 'warning' | 'success' | 'error' | 'info';
  title: string;
  content: string | VNode;
  okText?: string;
  cancelText?: string;
  okType?: string;
  onOk?: () => void;
  onCancel?: () => void;
  centered?: boolean;
  width?: number | string;
}
```

#### 使用示例

```vue
<script setup lang="ts">
import { useMessage } from '@/hooks/web';
import { h } from 'vue';

const { createConfirm } = useMessage();

// 基础确认框
const showConfirm = () => {
  createConfirm({
    iconType: 'warning',
    title: '确认删除',
    content: '删除后无法恢复，确定要删除吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      console.log('确认删除');
    },
  });
};

// 成功确认框
const showSuccessConfirm = () => {
  createConfirm({
    iconType: 'success',
    title: '操作成功',
    content: '数据已保存',
    okText: '好的',
  });
};

// 错误确认框
const showErrorConfirm = () => {
  createConfirm({
    iconType: 'error',
    title: '操作失败',
    content: '请检查网络连接',
  });
};

// 自定义内容
const showCustomConfirm = () => {
  createConfirm({
    iconType: 'info',
    title: '详细信息',
    content: h('div', [
      h('p', '这是一段自定义内容'),
      h('p', '可以包含多个元素'),
    ]),
  });
};
</script>
```

### 4. createConfirmSync 同步确认框

返回 Promise，支持 async/await。

```vue
<script setup lang="ts">
import { useMessage } from '@/hooks/web';

const { createConfirmSync } = useMessage();

// 使用 async/await
const handleDelete = async () => {
  const confirmed = await createConfirmSync({
    iconType: 'warning',
    title: '确认删除',
    content: '删除后无法恢复',
  });

  if (confirmed) {
    console.log('用户点击了确定');
    // 执行删除操作
  } else {
    console.log('用户点击了取消');
  }
};

// 在条件判断中使用
const handleSubmit = async () => {
  if (await createConfirmSync({
    title: '确认提交',
    content: '提交后无法修改',
  })) {
    // 提交数据
  }
};
</script>
```

### 5. Modal 模态框

#### 使用示例

```vue
<script setup lang="ts">
import { useMessage } from '@/hooks/web';

const {
  createSuccessModal,
  createErrorModal,
  createInfoModal,
  createWarningModal,
} = useMessage();

// 成功模态框
const showSuccessModal = () => {
  createSuccessModal({
    title: '操作成功',
    content: '数据保存成功',
  });
};

// 错误模态框
const showErrorModal = () => {
  createErrorModal({
    title: '操作失败',
    content: '网络连接失败，请检查网络设置',
  });
};

// 信息模态框
const showInfoModal = () => {
  createInfoModal({
    title: '系统信息',
    content: '系统将在今晚进行维护',
  });
};

// 警告模态框
const showWarningModal = () => {
  createWarningModal({
    title: '警告',
    content: '您的账户即将到期',
  });
};
</script>
```

## 完整示例

```vue
<template>
  <div class="message-demo">
    <a-space direction="vertical">
      <!-- 消息提示 -->
      <a-card title="消息提示">
        <a-space>
          <a-button @click="showSuccess">成功</a-button>
          <a-button @click="showError">错误</a-button>
          <a-button @click="showInfo">信息</a-button>
          <a-button @click="showWarning">警告</a-button>
          <a-button @click="showLoading">加载</a-button>
        </a-space>
      </a-card>

      <!-- 通知提示 -->
      <a-card title="通知提示">
        <a-space>
          <a-button @click="showSuccessNotify">成功通知</a-button>
          <a-button @click="showErrorNotify">错误通知</a-button>
          <a-button @click="showInfoNotify">信息通知</a-button>
        </a-space>
      </a-card>

      <!-- 确认框 -->
      <a-card title="确认框">
        <a-space>
          <a-button @click="showConfirm">普通确认</a-button>
          <a-button @click="handleAsyncConfirm">异步确认</a-button>
        </a-space>
      </a-card>

      <!-- 模态框 -->
      <a-card title="模态框">
        <a-space>
          <a-button @click="showSuccessModal">成功</a-button>
          <a-button @click="showErrorModal">错误</a-button>
          <a-button @click="showInfoModal">信息</a-button>
          <a-button @click="showWarningModal">警告</a-button>
        </a-space>
      </a-card>
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { useMessage } from '@/hooks/web';

const { createMessage, notification, createConfirm, createConfirmSync } = useMessage();
const { createSuccessModal, createErrorModal, createInfoModal, createWarningModal } = useMessage();

// 消息提示
const showSuccess = () => createMessage.success('操作成功');
const showError = () => createMessage.error('操作失败');
const showInfo = () => createMessage.info('这是一条提示');
const showWarning = () => createMessage.warning('请注意');
const showLoading = () => {
  const hide = createMessage.loading('加载中...');
  setTimeout(() => hide(), 2000);
};

// 通知提示
const showSuccessNotify = () => {
  notification.success({
    message: '成功',
    description: '操作成功',
  });
};
const showErrorNotify = () => {
  notification.error({
    message: '失败',
    description: '操作失败',
  });
};
const showInfoNotify = () => {
  notification.info({
    message: '提示',
    description: '这是一条通知',
  });
};

// 确认框
const showConfirm = () => {
  createConfirm({
    iconType: 'warning',
    title: '确认操作',
    content: '确定要执行此操作吗？',
    onOk: () => createMessage.success('确认'),
  });
};

const handleAsyncConfirm = async () => {
  const confirmed = await createConfirmSync({
    title: '确认删除',
    content: '删除后无法恢复',
  });

  if (confirmed) {
    createMessage.success('已删除');
  } else {
    createMessage.info('已取消');
  }
};

// 模态框
const showSuccessModal = () => createSuccessModal({ title: '成功', content: '操作成功' });
const showErrorModal = () => createErrorModal({ title: '失败', content: '操作失败' });
const showInfoModal = () => createInfoModal({ title: '信息', content: '系统信息' });
const showWarningModal = () => createWarningModal({ title: '警告', content: '请注意' });
</script>
```

## 注意事项

1. **国际化**：`okText` 和 `cancelText` 默认使用国际化配置
2. **自动关闭**：通知默认 3 秒后自动关闭
3. **HTML 内容**：内容支持 HTML 字符串（需确保内容安全）
4. **图标类型**：`iconType` 支持 warning、success、error、info
5. **异步确认**：使用 `createConfirmSync` 支持异步操作

## 相关文档

- [Ant Design Vue Message](https://antdv.com/components/message-cn)
- [Ant Design Vue Modal](https://antdv.com/components/modal-cn)
- [Ant Design Vue Notification](https://antdv.com/components/notification-cn)

---

*文档版本: 1.0.0*
*最后更新: 2026-01-10*
