❀❀❀❀❀❀❀❀
在開發中,經常遇到報錯提示,重複點擊,彈出多個message,很影響視覺效果,以下是總結出來的重置message方法!僅供參考,若有更好的方式歡迎大家留言!
實現思路:判斷彈窗是否已經存在,若存在先關閉,再重新打開新的彈窗,這樣就不會有重複的彈窗出現
❀❀❀❀❀❀❀❀
一、在tools中新建文件resetMessage.js(位置可隨意)
/**重置message,防止重复点击重复弹出message弹框 */
import { Message } from 'element-ui'
let messageInstance = null
let mainMessage = function DoneMessage (options) {
//如果弹窗已存在先关闭
if (messageInstance) {
messageInstance.close()
}
messageInstance = Message(options)
}
let arr = ['success', 'warning', 'info', 'error']
arr.forEach(function (type) {
mainMessage[type] = function (options) {
if (typeof options === 'string') {
options = { message: options }
}
options.type = type
return mainMessage(options)
}
})
export const message = mainMessage
二、引用
1.引用
使用時引入
import { message } from './resetMessage'
若全局使用可在main.js中引用,這裡只想局部使用,所以單獨引在特殊文件中
2.使用
使用就按正常應用Message一樣,自己定義了一下全局的$baseMessage
bus.js文件
import Vue from 'vue'
const $EventBus = new Vue()
// Vue.prototype.$EventBus = $EventBus
export default $EventBus
export function bindBusGloble (Vue) {
Vue.prototype.$EventBus = $EventBus;
}
main.js中使用引入並使用
import initGloble from './tools/gloable'
initGloble(Vue)
在gloable.js中定義全局事件initGloble ,若想定義其他全局事件,也可寫在initGloble中
Vue.prototype.$baseMessage此部分為核心內容,沒特殊需求的寶寶,只需要使用這段代碼即可!
import { bindBusGloble } from './bus.js';
import { message } from './resetMessage'
export default function initGloble (Vue) {
bindBusGloble(Vue);
/* 全局Message */
Vue.prototype.$baseMessage = (messages, type) => {
message({
offset: 60,
showClose: true,
message: messages,
type: type,
dangerouslyUseHTMLString: true,
duration: 3000,
})
}
}
在彈窗時就可以使用Vue.prototype.$baseMessage代替this.$message.error()了
Vue.prototype.$baseMessage('網絡錯誤,請重試', 'error')