我们在一个页面中也许会请求多条数据,如果出现token过期或返回异常错误的时候,使用拦截器拦截报错就会使message组件重复弹出。
下面我们将对这个问题进行一个简单处理:修改后只返回一个弹窗。
注:这里选用的是Element-UI中的Message
和Notify
组件(其他组件也类似)
创建src/utils/resetPopup.js
import Vue from 'vue';
/**重置message,防止重复点击重复弹出message弹框 */
let messageInstance = null;
const resetMessage = (options) => {
//关闭上一个弹窗,继续下一个弹窗
if (messageInstance) {
messageInstance.close() //手动关闭实例,调用它的 close 方法,详细内容请参考Element-ui官方文档。
}
messageInstance = Vue.prototype.$message(options)
};
['error', 'success', 'info', 'warning'].forEach(type => {
resetMessage[type] = options => {
if (typeof options === 'string') {
options = {
message: options
}
}
options.type = type
return resetMessage(options)
}
})
export const Message = resetMessage;
/**重置Notify,防止重复点击重复弹出Notify弹框 */
let notifyInstance = null;
const resetNotify = (options) => {
//关闭上一个弹窗,继续下一个弹窗
if (notifyInstance) {
notifyInstance.close() //手动关闭实例,调用它的 close 方法,详细内容请参考Element-ui官方文档。
}
notifyInstance = Vue.prototype.$notify(options)
};
['error', 'success', 'info', 'warning'].forEach(type => {
resetNotify[type] = options => {
if (typeof options === 'string') {
options = {
title: options
}
}
options.type = type
return resetNotify(options)
}
})
export const Notify = resetNotify;
使用方式
import { Message , Notify } from '@/utils/resetPopup' //重置弹窗
Message({
message: response.data.msg,
type: 'error',
duration: 2000
})
Notify({
title: response.data.msg,
type: 'error',
duration: 2000
})