vue3 + Element Plus + ts 封装全局的 message、messageBox、notification 方法

本文示例将 Element Plus 中的 ElMessage 消息提示, ElMessageBox 消息弹出框, ElNotification 消息通知 方法统一封装到全局 hooks 文件中方便全局调用

准备在项目 src 目录中新建 hooks 目录、然后在 hooks 目录中新建 index.ts (如果你没有使用 ts 也可以建 index.js)文件(主要用于将全局的方法放到这个文件中),当然,你可以根据自己的习惯或喜好将示例代码放置到其他地方。

完整代码(ts 版)

// 用于封装一些全局的hook,可以单独导入某些方法使用,也可以统一导入 hook 对象,从 hook 对象中 . 具体的方法

import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'

/**
 * 封装一个全局的 message 方法,用于显示消息提示
 * @param message 消息内容
 * @param type 消息类型,默认为 success
 * @param [options] 消息选项
 */
export const message = (
  message: string,
  type: 'success' | 'warning' | 'info' | 'error' = 'success',
  options: any = {}
) => {
  ElMessage({
    message,
    type,
    ...options
  })
}
/**
 * 封装一个全局的 confirm 方法,用于显示确认对话框
 * @param message 对话框内容
 * @param title 对话框标题,默认为 '提示'
 * @param [options] 对话框选项
 * @return Promise<boolean>
 */
export const confirm = (message: string, title: string = '提示', options: any = {}) => {
  if (Object.keys(options).length === 0) {
    options = {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  }
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(message, title, options)
      .then(() => {
        resolve(true)
      })
      .catch(() => {
        reject(false)
      })
  })
}
/**
 * 封装一个全局的 notification 方法,用于显示通知
 * @param message 通知内容
 * @param title 通知标题,默认为 '提示'
 * @param [options] 通知选项
 */
export const notification = (message: string, title: string = '提示', options: any = {}) => {
  ElNotification({
    title,
    message,
    ...options
  })
}

/**
 * 统一导出一个 hook 方法对象,包含所有 hook 方法
 */
export default {
  message,
  confirm,
  notification
}

注:这是完整代码,如果你的项目也是 vue3 + Element Plus + ts 那么你可以直接全部复制放到你创建的 .ts 文件中,然后在页面中导入使用它们。

使用示例

导入(注意核实你的文件路径)

import hooks from '@/hooks/index'

使用示例

hooks.message('操作成功') // 成功弹出

hooks.notification('恭喜你学会了使用全局通知组件', '操作成功', { type: 'success' }) // 成功弹出

hooks.confirm('确认要删除吗?').then((res) => console.log(res)) // 成功弹出

注:使用时也可以根据 Element Plus 官方文档的配置项传入你需要的配置,按方法参数格式传入即可

### 使用 Vue 3Element Plus 实现全局通知功能 为了在 Vue 3 项目中集成并使用 Element Plus 的 `ElNotification` 组件实现全局通知效果,可以按照如下方式设置: #### 安装依赖包 确保已经安装了必要的开发工具和库。如果尚未初始化项目,则可以通过命令创建新项目[^2]。 对于已有项目,在终端执行以下命令以添加 Element Plus 到当前工程环境中: ```bash npm install element-plus --save ``` #### 导入样式文件 为了让应用程序能够正确显示 Element Plus 提供的通知样式,需导入其 CSS 文件到项目的入口文件(通常是 main.ts 或者 main.js)。这一步骤非常重要,因为默认情况下不会自动引入这些资源。 ```typescript // main.ts or main.js import &#39;element-plus/dist/index.css&#39;; ``` #### 创建全局通知服务 定义一个新的 JavaScript/TypeScript 模块用于管理所有的通知逻辑。这里展示了一个简单的例子,其中包含了打开成功提示、错误警告等功能的方法。 ```typescript // src/utils/notificationService.ts import { ElNotification } from "element-plus"; const NotificationService = { success(message: string, title?: string): void { ElNotification({ type: &#39;success&#39;, message, title: title || &#39;Success&#39; }); }, error(message: string, title?: string): void { ElNotification({ type: &#39;error&#39;, message, title: title || &#39;Error&#39; }); } }; export default NotificationService; ``` #### 应用程序中的调用 一旦完成了上述准备工作之后,就可以在整个应用的不同地方轻松地触发各种类型的弹窗消息了。下面是一个组件内部的例子,它会在点击按钮时发出一条成功的反馈信息给用户。 ```html <template> <div class="example"> <el-button @click="handleClick">Show Success Message</el-button> </div> </template> <script lang="ts"> import { defineComponent } from &#39;vue&#39;; import notificationService from &#39;@/utils/notificationService&#39;; export default defineComponent({ name: &#39;ExampleComponent&#39;, methods: { handleClick():void{ notificationService.success(&#39;This is a successful operation.&#39;); } } }); </script> ``` 通过这种方式,不仅可以让代码结构更清晰合理,而且也提高了可读性和重用率。同时利用 Element Plus 自带的主题定制能力还可以进一步调整外观风格使之更好地融入整体设计之中[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值