怎么樣讓Element UI的Message消息提示每次只彈出一個(gè)

這個(gè)問題非常的常見,使用過Element的都知道,頻繁點(diǎn)擊Message消息提示會(huì)出現(xiàn)以下這種情況:

Snipaste_2020-06-12_16-31-30.png

怎么處理呢?為了防止用戶頻繁點(diǎn)擊,或者頻繁的提交表單給的提示,查看了官方文檔確實(shí)沒有提供彈出一次的功能。

解決方案
通過對(duì)Message分析可以得知:Element UI在調(diào)用Message組件時(shí)會(huì)在HTML中插入以下代碼,

單個(gè)Message的時(shí)候:
Snipaste_2020-06-12_16-37-36.png

多個(gè)Message的時(shí)候:
Snipaste_2020-06-12_16-39-51.png

這樣子我們就可以通過這個(gè)元素是否存在來進(jìn)行一個(gè)判斷,如果存在就不要讓他繼續(xù)添加,這是一種思路,接下來就是代碼的實(shí)現(xiàn)。

注意事項(xiàng)
這個(gè)代碼應(yīng)該是在你引入element的地方寫的,有些是把element單獨(dú)抽出一個(gè)文件來按需引入,然后再去main.js進(jìn)行引入,有的是直接在main.js直接引入element,看自己的愛好,我的是第一種情況所以我把下面的代碼寫到了單獨(dú)抽離出來的element.js文件中。

文件結(jié)構(gòu)

Snipaste_2020-06-12_16-50-58.png

Snipaste_2020-06-12_16-53-11.png

//在element.js文件

import Vue from "vue";
import "element-ui/lib/theme-chalk/index.css";
import {Pagination,Dialog,Autocomplete,Dropdown,DropdownMenu,DropdownItem,Message} from "element-ui";

//解決Message彈出多個(gè)提示框
const showMessage = Symbol("showMessage");
class DonMessage {
  success(options, single = true) {
    this[showMessage]("success", options, single);
  }
  warning(options, single = true) {
    this[showMessage]("warning", options, single);
  }
  info(options, single = true) {
    this[showMessage]("info", options, single);
  }
  error(options, single = true) {
    this[showMessage]("error", options, single);
  }

  [showMessage](type, options, single) {
    if (single) {
      // 判斷是否已存在Message
      if (document.getElementsByClassName("el-message").length === 0) {
        Message[type](options);
      }
    } else {
      Message[type](options);
    }
  }
}

Vue.use(Pagination);
Vue.use(Dialog);
Vue.use(Autocomplete);
Vue.use(Dropdown);
Vue.use(DropdownMenu);
Vue.use(DropdownItem);

Vue.prototype.$loading = Loading.service;
Vue.prototype.$msgbox = MessageBox;
Vue.prototype.$alert = MessageBox.alert;
Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;
Vue.prototype.$notify = Notification;
// Vue.prototype.$message = Message;
// 命名根據(jù)需要,DonMessage只是在文章中使用
Vue.prototype.$message = new DonMessage()

調(diào)用方式

因?yàn)槭褂昧薾ew DonMessage()的原因,所以導(dǎo)致this.message(options)的方式無法使用。所以推薦使用this.message.success('成功提示')或者this.$message.success(options)的方式進(jìn)行調(diào)用。具體參數(shù)可以查看官方文檔。

Snipaste_2020-06-12_17-10-58.png

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容