• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue3 防止elMessage 弹窗多次弹出

武飞扬头像
一路☞向北
帮助1

相信很多小伙伴在做项目的时候都会遇到一个问题,那就是我们使用 elment ui 或者 element-plus 的时候,使用里面的弹窗组件,在同一按钮多次点击的时候,会触发很多次这个弹窗,看着很不舒服,哈哈。 所以我就想着能不能找到解决的办法,终于, 功夫不负有心人,让我找到了。下面我就来展示下我找到的解决办法。

1. 首先在utils文件夹里面封装一个 重置弹窗的 js 文件。 名字: resetMessage.js

  1.  
     
  2.  
    import { ElMessage } from 'element-plus' //引入message弹出框
  3.  
     
  4.  
    let messageDom = null
  5.  
    const resetMessage = (options) => {
  6.  
    if (messageDom) messageDom.close() // 判断弹窗是否已存在,若存在则关闭
  7.  
    messageDom = ElMessage(options)
  8.  
    }
  9.  
    const typeArr = ['success', 'error', 'warning', 'info']
  10.  
    typeArr.forEach(type => {
  11.  
    resetMessage[type] = options => {
  12.  
    if (typeof options === 'string') options = { message: options }
  13.  
    options.type = type
  14.  
    return resetMessage(options)
  15.  
    }
  16.  
    })
  17.  
    export const message = resetMessage
  18.  
     
学新通

2. 在 main.js 引入,并挂载

  1.  
     
  2.  
    import { message } from '@/utils/resetMessage.js'
  3.  
     
  4.  
     
  5.  
    const app = createApp(App)
  6.  
    app.config.globalProperties.$msg = message; // 挂载
  7.  
     

3. 在需要使用弹窗的组件进行使用,但是需要引入 getCurrentInstance, 通过proxy.$msg来调用

  1.  
    import { getCurrentInstance } from 'vue'
  2.  
     
  3.  
    setup(){
  4.  
     
  5.  
    const { proxy } = getCurrentInstance();// ctx中有问题,建议使用proxy中获取
  6.  
     
  7.  
    // 登录
  8.  
    const onSubmit = (formRef) => {
  9.  
    formRef.validate(async (valid) => {
  10.  
    if (valid) {
  11.  
    const { data: res } = await _login(form)
  12.  
    if (res.meta.status !== 200) ElMessage.error('账号或密码错误')
  13.  
    window.sessionStorage.setItem("active", 'welcome');
  14.  
    store.commit("user/setToken",res.data)
  15.  
    proxy.$msg.success(res.meta.msg)
  16.  
    router.push('/home')
  17.  
    } else {
  18.  
    return false
  19.  
    }
  20.  
    })
  21.  
    }
  22.  
     
  23.  
    return { onSubmit}
  24.  
     
  25.  
    }
学新通

亲测,有效,有帮助到的小伙伴,点点小爱心,加油!

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhihcfgc
系列文章
更多 icon
同类精品
更多 icon
继续加载