详细分析Element Plus中的ElMessageBox弹窗用法(附Demo及模版)

目录

  • 前言
  • 1. 基本知识
  • 2. Demo
  • 3. 实战
  • 4. 模版

前言

由于需要在登录时,附上一些用户说明书的弹窗
对于ElMessageBox的基本知识详细了解
可通过官网了解基本的语法知识ElMessageBox官网基本知识

1. 基本知识

Element Plus 是一个基于 Vue 3 的组件库,其中包括各种类型的弹窗组件,用于在网页上显示信息或与用户进行交互

主要的弹窗组件包括 ElMessageBox.alert、ElMessageBox.prompt 和 ElMessageBox.confirm 等

  • ElMessageBox.prompt
    用于显示带有输入框的对话框
    用于需要用户输入信息的场景
import { ElMessageBox } from 'element-plus'

ElMessageBox.prompt(
  '请输入你的邮箱',
  '提示',
  {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }
).then(({ value }) => {
  console.log('用户输入的邮箱:', value)
}).catch(() => {
  console.log('取消输入')
})
  • ElMessageBox.alert
    用于显示带有确认按钮的对话框
    用于告知用户某些信息
import { ElMessageBox } from 'element-plus'

ElMessageBox.alert(
  '这是一段内容',
  '标题',
  {
    confirmButtonText: '确定',
    callback: action => {
      console.log(action)
    }
  }
)
  • ElMessageBox.confirm
    用于显示带有确认和取消按钮的对话框
    用于需要用户确认或取消某些操作的场景
import { ElMessageBox } from 'element-plus'

ElMessageBox.confirm(
  '此操作将永久删除该文件, 是否继续?',
  '提示',
  {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }
).then(() => {
  console.log('确认')
}).catch(() => {
  console.log('取消')
})

对于上述基本参数

参数描述
title对话框的标题
message对话框的消息内容,可以是字符串或 HTML
type消息类型,如 success, info, warning, error
iconClass自定义图标的类名
customClass对话框自定义类名
showClose是否显示右上角关闭按钮,默认为 true
closeOnClickModal是否可以通过点击遮罩层关闭对话框,默认为 true
closeOnPressEscape是否可以通过按下 Esc 键关闭对话框,默认为 true
showCancelButton是否显示取消按钮,默认为 false
cancelButtonText取消按钮的文本内容
confirmButtonText确认按钮的文本内容
cancelButtonClass自定义取消按钮的类名
confirmButtonClass自定义确认按钮的类名
beforeClose关闭前的回调函数,可以用于阻止对话框的关闭
callback对话框关闭时的回调函数
inputPlaceholder输入框的占位符(仅用于 prompt)
inputValue输入框的初始值(仅用于 prompt)
inputType输入框的类型(仅用于 prompt)
inputPattern输入框的校验正则表达式(仅用于 prompt)
inputValidator输入框的校验函数(仅用于 prompt)
inputErrorMessage输入框校验失败时的错误提示(仅用于 prompt)

2. Demo

对应的Demo示例:

  • ElMessageBox.prompt
import { ElMessageBox } from 'element-plus'

const showPrompt = () => {
  ElMessageBox.prompt(
    '请输入你的名字',
    '输入框',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '名字',
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
    }
  ).then(({ value }) => {
    console.log('输入的名字:', value)
  }).catch(() => {
    console.log('已取消')
  })
}
  • ElMessageBox.alert
import { ElMessageBox } from 'element-plus'

const showAlert = () => {
  ElMessageBox.alert(
    '操作成功',
    '提示',
    {
      confirmButtonText: '确定',
      type: 'success',
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
    }
  ).then(() => {
    console.log('已确认')
  })
}
  • ElMessageBox.confirm
import { ElMessageBox } from 'element-plus'

const showConfirm = () => {
  ElMessageBox.confirm(
    '是否确认删除此项?',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          // 执行一些操作
          done()
        } else {
          done()
        }
      }
    }
  ).then(() => {
    console.log('已确认')
  }).catch(() => {
    console.log('已取消')
  })
}

如果需要自定义的样式,可通过如下:

ElMessageBox.confirm(
  '内容',
  '标题',
  {
    customClass: 'my-custom-class',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }
)

css如下:

.my-custom-class .el-message-box__btns {
  justify-content: center;
}
.my-custom-class .el-button--primary {
  width: 100%;
  margin: 0;
}

3. 实战

const handleLogin = async (params) => {
  loginLoading.value = true
  try {
    await getTenantId()
    const data = await validForm()
    if (!data) {
      return
    }
    loginData.loginForm.captchaVerification = params.captchaVerification
    const res = await LoginApi.login(loginData.loginForm)
    if (!res) {
      return
    }
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (loginData.loginForm.rememberMe) {
      authUtil.setLoginForm(loginData.loginForm)
    } else {
      authUtil.removeLoginForm()
    }
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      push({ path: redirect.value || permissionStore.addRouters[0].path })
    }
  } finally {
    loginLoading.value = false
    loading.value.close()
    // 登录成功后显示弹窗提示
    await ElMessageBox.confirm(
      `<div>
        <p>尊敬的客户:<br><br>
        您好!xxxx前认真阅读以下须知:<br><br>
        1xxxxxx<br><br>
        <input type="checkbox" id="agree-checkbox" /> <label for="agree-checkbox">我已认真阅读并知悉以上须知</label>
        </p>
      </div>`,
      'xxx须知', 
      {
        confirmButtonText: '同意',
        showClose: false, // 禁止关闭
        showCancelButton: false, // 隐藏右上角的关闭按钮
        closeOnClickModal: false, // 禁止点击遮罩层关闭
        closeOnPressEscape: false, // 禁止按下 Esc 键关闭
        dangerouslyUseHTMLString: true,
        customClass: 'full-width-button', // 添加自定义类名
        beforeClose: (action, instance, done) => {
          if (action === 'confirm' && !document.getElementById('agree-checkbox').checked) {
            instance.confirmButtonLoading = false
            return ElMessageBox.alert('请勾选“我已认真阅读并知悉以上须知”以继续', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
          done()
        }
      }
    );
  }
}

// 添加样式以使按钮占据整个宽度
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `
  .el-message-box.full-width-button .el-message-box__btns {
    display: flex;
    justify-content: center;
  }
  .el-message-box.full-width-button .el-button--primary {
    width: 100%;
    margin: 0;
  }
`;
document.head.appendChild(style);

总体截图如下:

在这里插入图片描述

下半部分的截图如下:

在这里插入图片描述

4. 模版

针对上述应用的需求,可以附实战的Demo

import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { useI18n } from './useI18n'
export const useMessage = () => {
  const { t } = useI18n()
  return {
    // 消息提示
    info(content: string) {
      ElMessage.info(content)
    },
    // 错误消息
    error(content: string) {
      ElMessage.error(content)
    },
    // 成功消息
    success(content: string) {
      ElMessage.success(content)
    },
    // 警告消息
    warning(content: string) {
      ElMessage.warning(content)
    },
    // 弹出提示
    alert(content: string) {
      ElMessageBox.alert(content, t('common.confirmTitle'))
    },
    // 错误提示
    alertError(content: string) {
      ElMessageBox.alert(content, t('common.confirmTitle'), { type: 'error' })
    },
    // 成功提示
    alertSuccess(content: string) {
      ElMessageBox.alert(content, t('common.confirmTitle'), { type: 'success' })
    },
    // 警告提示
    alertWarning(content: string) {
      ElMessageBox.alert(content, t('common.confirmTitle'), { type: 'warning' })
    },
    // 通知提示
    notify(content: string) {
      ElNotification.info(content)
    },
    // 错误通知
    notifyError(content: string) {
      ElNotification.error(content)
    },
    // 成功通知
    notifySuccess(content: string) {
      ElNotification.success(content)
    },
    // 警告通知
    notifyWarning(content: string) {
      ElNotification.warning(content)
    },
    // 确认窗体
    confirm(content: string, tip?: string) {
      return ElMessageBox.confirm(content, tip ? tip : t('common.confirmTitle'), {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })
    },
    // 删除窗体
    delConfirm(content?: string, tip?: string) {
      return ElMessageBox.confirm(
        content ? content : t('common.delMessage'),
        tip ? tip : t('common.confirmTitle'),
        {
          confirmButtonText: t('common.ok'),
          cancelButtonText: t('common.cancel'),
          type: 'warning'
        }
      )
    },
    // 导出窗体
    exportConfirm(content?: string, tip?: string) {
      return ElMessageBox.confirm(
        content ? content : t('common.exportMessage'),
        tip ? tip : t('common.confirmTitle'),
        {
          confirmButtonText: t('common.ok'),
          cancelButtonText: t('common.cancel'),
          type: 'warning'
        }
      )
    },
    // 提交内容
    prompt(content: string, tip: string) {
      return ElMessageBox.prompt(content, tip, {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })
    }
  }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/647686.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

初识C语言——第二十四天

函数的基本使用和递归 1.函数是什么 2.库函数 3.自定义函数 4.函数参数 5.函数调用 6.函数的嵌套调用和链式访问 7.函数的声明和定义 函数是什么 C语言中函数的分类 1.库函数 2.自定义函数 库函数&#xff1a; 简单的总结,C语言常用的库函数都有&#xff1a; #includ…

QT之常用控件

一个图形化界面当然需要有各种各样的控件&#xff0c;QT也不例外&#xff0c;在QT designer中就有提供各种各样的控件&#xff0c;用以开发图形化界面。 而想使用好一个QT控件&#xff0c;就需要了解这些控件。 QWidget 在QT中&#xff0c;所有控件都继承自 QWidget 类&…

Docker学习(4):部署web项目

一、部署vue项目 在home目录下创建项目目录 将打包好的vue项目放入该目录下&#xff0c;dist是打包好的vue项目 在项目目录下&#xff0c;编辑default.conf 内容如下&#xff1a; server {listen 80;server_name localhost; # 修改为docker服务宿主机的iplocation / {r…

24法考证件照要求|不合格原因汇总!

6月法考报名&#xff0c;大家一定要提前熟悉下电子证件照片要求‼️ ⚠️证件照注意事项 ▪️不得上传全身照、风景照、生活照、背带(吊带)衫照、艺术照、侧面照、不规则手机照等。 ▪️本人近三个月内彩色(红、蓝、白底色均可)正面免冠电子证件照片&#xff0c;照片必须清晰完…

人工智能为犯罪地下世界带来了巨大的生产力提升

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…

MySQL--执行计划

一、执行计划 1.介绍 执行计划是sql在执行时&#xff0c;优化器优化后&#xff0c;选择的cost最低的方案 通过desc、explain可以查看sql的执行计划 2.如何查看执行计划 table语句操作的表&#xff0c;在多表时才有意义type查找类型possible_keys可能会用到的索引key最终选择的…

python ofd转pdf及图片

本文部分内容参考&#xff0c;如有侵权请联系删除&#xff1a;使用 easyofd 解析ofd 文件_python模块easyofd如何使用-CSDN博客 背景需求&#xff1a;需要将邮箱中得ofd格式发票提取出来转换成pdf或者图片。 在网上搜了发现使用pyofd包&#xff0c;安装之后使用各种问题&…

VXLAN小结

1.VXLAN:(组件虚拟网络的架构核心)虚拟扩展本地局域网&#xff0c;通过隧道的形式&#xff0c;将物理上有隔离的资源&#xff0c;在逻辑上连通起来&#xff0c;使其二层互通。 a.物理网络:指的是构成 VXLAN 连接的基础 IP 网络 b.逻辑网络:指的是通过 VXLAN 构建的虚拟网络 C.N…

腾讯Java社招面试题真题,最新面试题

Java中synchronized和ReentrantLock有什么区别&#xff1f; 1、锁的实现方式不同&#xff1a; synchronized是JVM层面的锁&#xff0c;主要依赖于监视器对象&#xff08;monitor&#xff09;实现。ReentrantLock是JDK层面的锁&#xff0c;通过Java代码实现&#xff0c;提供了更…

docker 上面安装 Nginx 以及设置访问 IP 就可以访问前端工程

docker 运行 Nginx 第一步&#xff1a;搜索下镜像 首先可以使用 docker search nginx 搜索 nginx 服务 docker search nginx相关控制台输出&#xff1a; NAME DESCRIPTION STARS OFFICIAL…

[OC]深拷贝与浅拷贝

深拷贝与浅拷贝 深拷贝与浅拷贝 深拷贝与浅拷贝定义按照类型说明非容器类对象的深拷贝与浅拷贝不可变字符串可变类型字符串 容器类对象的深浅拷贝自定义类对象的深浅拷贝容器类对象的完全深拷贝1.copyItems2.解档和归档 定义 深拷贝&#xff1a;简单来说就是创建一个与被复制对…

虚拟化技术[2]之存储虚拟化

存储虚拟化 存储虚拟化简介存储虚拟化一般模型存储虚拟化实现方式基于主机存储虚拟化基于存储设备存储虚拟化基于网络存储虚拟化 案例分析&#xff1a;VMFSVMFS功能 存储虚拟化简介 存储虚拟化&#xff1a;将存储网络中的各个分散且异构的存储设备按照一定的策略映射成一个统一…

webpack5生产模式

生产模式 生产模式准备 开发模式和生产模式有不同的 配置文件 2修改webpack.prod.js文件修改webpack.dev.js文件 修改webpack.dev.js文件 1》修改输出路径为undefined 2》将绝对路径进行修改&#xff0c;进行回退 此时文件的执行命令为 修改webpack.prod.js文件 1》修改绝…

LangChain笔记

很好的LLM知识博客&#xff1a; https://lilianweng.github.io/posts/2023-06-23-agent/ LangChain的prompt hub: https://smith.langchain.com/hub 一. Q&A 1. Q&A os.environ["OPENAI_API_KEY"] “OpenAI的KEY” # 把openai-key放到环境变量里&…

【Linux】Linux的基本指令_2

文章目录 二、基本指令8. man9. nano 和 cat10. cp11. mv12. echo 和 > 和 >> 和 <13. more 和 less14. head 和 tail 和 | 未完待续 二、基本指令 8. man Linux的命令有很多参数&#xff0c;我们不可能全记住&#xff0c;我们可以通过查看联机手册获取帮助。访问…

深入编程逻辑:从分支到循环的奥秘

新书上架~&#x1f447;全国包邮奥~ python实用小工具开发教程http://pythontoolsteach.com/3 欢迎关注我&#x1f446;&#xff0c;收藏下次不迷路┗|&#xff40;O′|┛ 嗷~~ 目录 一、编程逻辑的基石&#xff1a;分支与循环 分支逻辑详解 代码案例&#xff1a;判断整数是…

Unity 资源 之 限时免费的Lowpoly农场动物,等你来领!

Unity资源 之 Lowpoly farm animals 农村动物 前言资源包内容领取兑换码 前言 Unity 资源商店为大家带来了一份特别的惊喜——限时免费的农场动物资源&#xff01;这是一个充满趣味和实用性的资源包。 资源包内容 在这个资源包中&#xff0c;你可以找到丰富多样的低地养殖动物…

685. 冗余连接 II

685. 冗余连接 II 问题描述 在本问题中&#xff0c;有根树指满足以下条件的 有向 图。该树只有一个根节点&#xff0c;所有其他节点都是该根节点的后继。该树除了根节点之外的每一个节点都有且只有一个父节点&#xff0c;而根节点没有父节点。 输入一个有向图&#xff0c;该…

mac 安装Node.js

文章目录 前言一、Node是什么&#xff1f;二、下载三、安装四、验证总结 前言 Node.js是一个开源、跨平台的JavaScript运行时环境&#xff0c;它允许开发者在服务器端运行JavaScript代码。Node.js是基于Chrome V8 JavaScript引擎构建的&#xff0c;它的设计目标是提供一种高效…

这样的直男程序员,活该你单身一万年!

#分享下相亲时遇到过哪些奇葩现象# 这样的直男程序员&#xff0c;活该你单身一万年&#xff01; 在丛丛脱单小程序上相亲&#xff0c;遇到一个程序员妹纸&#xff0c;于是有了如下的真实故事&#xff1a; 妹子说她是程序员来着&#xff0c;想着我也是程序员&#xff0c;就想交…