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

news2024/9/23 17:20:07

目录

  • 前言
  • 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.coloradmin.cn/o/1695982.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C++ Primer Plus第十八章复习题

1、使用用大括号括起的初始化列表语法重写下述代码。重写后的代码不应使用数组ar。 class z200 { private:int j;char ch;double z; public:Z200(int jv,char chv&#xff0c;zv) : j(jv), ch (chv), z(zv){} };double x 8.8; std::string s "what a bracing effect ! …

前端---闭包【防抖以及节流】----面试高频!

1.什么闭包 释放闭包 从以上看出&#xff1a;一般函数调用一次会把内部的数据进行清除--但是这种操作却可以一起保留局部作用域的数据 // 优点:1、可以读取函数内部的变量 2、让这些变量始中存在局部作用域当中 2.闭包产生的两种业务场景&#xff1a;防抖、节流 2.1防抖 举…

Mysql教程(0):学习框架

1、Mysql简介 MySQL 是一个开放源代码的、免费的关系型数据库管理系统。在 Web 开发领域&#xff0c;MySQL 是最流行、使用最广泛的关系数据库。MySql 分为社区版和商业版&#xff0c;社区版完全免费&#xff0c;并且几乎能满足全部的使用场景。由于 MySQL 是开源的&#xff0…

【Windows】 IDimager Photo Supreme 2024(图片管理软件)安装教程

软件介绍 IDimager Photo Supreme 2024是一款专业的图片管理软件&#xff0c;旨在帮助用户有效地组织、管理和浏览他们的照片收藏。以下是该软件的一些主要特点和功能&#xff1a; 图片管理&#xff1a;Photo Supreme提供强大的图片管理功能&#xff0c;可以帮助用户轻松地整理…

笔记89:LeetCode_135_分发糖果

前言&#xff1a; 注&#xff1a;代码随想录中没有很清楚的提起想出方法的思路&#xff0c;只是给出了解决这个问题的大致思路和代码&#xff1b;下面我将介绍一下我的思考过程&#xff0c;并贴出实现代码&#xff1b; a a a a 思考过程&#xff1a; 思路1&#xff1a;为了…

Win32 API

个人主页&#xff1a;星纭-CSDN博客 系列文章专栏 : C语言 踏上取经路&#xff0c;比抵达灵山更重要&#xff01;一起努力一起进步&#xff01; 一.Win32 API 1.Win32 API介绍 Windows这个多作业系统除了协调应⽤程序的执⾏、分配内存、管理资源之外&#xff0c;它同时也是…

【408真题】2009-15

“接”是针对题目进行必要的分析&#xff0c;比较简略&#xff1b; “化”是对题目中所涉及到的知识点进行详细解释&#xff1b; “发”是对此题型的解题套路总结&#xff0c;并结合历年真题或者典型例题进行运用。 涉及到的知识全部来源于王道各科教材&#xff08;2025版&…

nginx服务器执行的过程

一:打包 1.打包前的分析 文件路径下npm run preview -- --report 生成打包之后的内容 2.解决有些内容体积过大的问题 1.删除有些不使用但是占用较多的,将main.js上import删除,打包时不会有 2.不能删除但是内容较大的 vue.config.js文件夹下 externals: { vue: Vue,…

mysql5.5版本安装过程

mysql是关系型数据库的管理系统 将安装包放在 c盘根目录 名称为mysql 在该路径下cmd进入命令执行窗口 出现此页面说明安装成功 需要修改配置文件内容 将my-medium.ini 复制粘贴并改名为 my.ini 并添加如下内容 改好之后在mysql目录下cmd进入命令执行窗口 切换到cd bin …

[集群聊天服务器]----(一)项目简介

在最近的学习中&#xff0c;实现了基于muduo网络库的集群聊天服务器&#xff0c;在此做一个剖析以及相关内容的梳理介绍&#xff0c;希望可以帮助到大家。 这一篇&#xff0c;先来简单介绍一下这个项目。 源码地址 Cluster_Chat_System-项目 项目技术特点 使用C开发并基于 …

ASP+ACCESS公司门户网站建设

【摘 要】随着计算机科学的发展&#xff0c;数据库技术在Internet中的应用越来越广泛&#xff0c;为广大网络用户提供了更加周到和人性化的服务。本文讲解了一个公司的网站的建设&#xff0c;它基于数据关联规则的公司个性化页面及动态数据生成案例&#xff0c;在网页方面&…

Linux--线程的认识(一)

线程的概念 线程&#xff08;Thread&#xff09;是操作系统中进行程序执行的最小单位&#xff0c;也是程序调度和分派的基本单位。它通常被包含在进程之中&#xff0c;是进程中的实际运作单位。一个线程指的是进程中一个单一顺序的控制流&#xff0c;一个进程中可以并发多个线…

Django与前端框架协作开发实战:高效构建现代Web应用

title: Django与前端框架协作开发实战&#xff1a;高效构建现代Web应用 date: 2024/5/22 20:07:47 updated: 2024/5/22 20:07:47 categories: 后端开发 tags: DjangoREST前端框架SSR渲染SPA路由SEO优化组件库集成状态管理 第1章&#xff1a;简介 1.1 Django简介 Django是一…

hive3从入门到精通(二)

第15章:Hive SQL Join连接操作 15-1.Hive Join语法规则 join分类 在Hive中&#xff0c;当下版本3.1.2总共支持6种join语法。分别是&#xff1a; inner join&#xff08;内连接&#xff09;left join&#xff08;左连接&#xff09;right join&#xff08;右连接&#xff09;…

04.爬虫---Session和Cookie

04.Session和Cookie 1.Session2.Cookie3.详细对比4.Cookie属性结构5.一些误区 Session和Cookie是Web开发中用于用户状态管理的两种常见技术。理解它们的区别对于开发安全的Web应用至关重要。 1.Session Session代表服务器与客户端的一次会话过程。服务器端存储了Session对象&…

智能合作:多AI协同助力传统工作流

背景介绍 红杉资本2024 AI AGENT大会上吴恩达再次介绍了AI四大设计模式即&#xff1a; 反思&#xff08;Reflection)&#xff1b;工具使用&#xff08;Tool use&#xff09;&#xff1b;规划&#xff08;Planning)&#xff1b;多智能体协作(Multi-agent collaboration)&#…

spring模块(三)Spring AOP(2)使用

一、demo 1、spring项目 &#xff08;1&#xff09;pom <dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>4.3.13.RELEASE</version></dependency>&l…

数据分析工程师——什么是数据分析?

数据分析工程师 对于目前就业市场上的技术岗位,除了开发、测试、运维等常见职位之外,数据类岗位也越来越成为热门的求职方向。本文将重点介绍 数据分析 这一新兴岗位。 看到「数据分析」这几个字,也许大家的第一印象一样,觉得要做的工作似乎并不难,有大量数据后根据业务…

Redis分布式存储方案

一、Redis分布式存储方案 1、哈希取余分区 ①、原理 哈希计算&#xff1a;首先&#xff0c;对每个键&#xff08;key&#xff09;进行哈希计算&#xff0c;得到一个整数哈希值&#xff08;hash value&#xff09;。取余操作&#xff1a;将这个哈希值对服务器数量进行取余操作…

AI播客下载:The Logan Bartlett Show Podcast(AI创业投资主题)

Logan Bartlett Show Podcast是一个播客&#xff0c;主持人Logan Bartlett与科技界的领导者以及投资者进行对话&#xff0c;讨论他们在运营或投资企业中学到的经验教训&#xff0c;主要集中在科技创投领域。 Logan Bartlett 是 Redpoint Ventures 的投资人&#xff0c;并且在该…