在Vue 中基于elementUI二次封装messagebox
需求描述
为了解决频繁点击某按钮不断触发事件调接口弹出提示语的问题,项目中希望可以在第一次点击调用接口成功之后弹出弹框类提示语并在3秒后自动消失,提示语未消失的情况下不能再次点击,为此,我基于elementui的messagebox进行了二次封装。(样式简略意思一下)
一、封装confirm.js
/** confirm.js */
import Vue from 'vue';
import { MessageBox } from 'element-ui'
// 传入参数:提示语 持续时间 提示语类型
function handleConfirm(msg="",duration=1000,type="success") {//设置默认值
if(type=='success'){
var str = `<p style="color:#1aa365;font-size:18px">${msg}</p>`;
}else{
var str = `<p style="color:#E71C1C;font-size:18px">${msg}</p>`;
}
MessageBox.confirm(str, "", {
dangerouslyUseHTMLString: true, //是否将 message 属性作为 HTML 片段处理
showConfirmButton: false, //去掉确定按钮
showCancelButton: false, //去掉取消按钮
center: true,
showClose: false,
})
.then(() => {
// 此处可再调一次查询方法
})
.catch((err) => {console.log(err);});
return new Promise((resolve,reject)=>{
setTimeout(()=> {
let closeBtn =document.body.getElementsByClassName("v-modal")[0];
closeBtn.click();
resolve();
}, duration);
})
}
function registryConfirm() {
// 将组件注册到 vue 的 原型链里去,
// 这样就可以在所有 vue 的实例里面使用 this.$toConfirm() //避免影响原项目的其他已用到了$confirm的地方,起名错开
Vue.prototype.$toConfirm = handleConfirm
}
export default registryConfirm;
二、在入口文件main.js处引入
import registryConfirm from '@/common/confirm.js';
Vue.use(registryConfirm)
三、在组件中使用
this.axios
.post(
this.http + "...",
this.qs.stringify(data)
)
.then((res) => {
// console.log('登录成返回的数据' , res);
if (res.code == 0) {
this.$toConfirm(res.msg,3000,'success')
} else {
this.$toConfirm(res.msg,3000,'error')
}
})
.catch((err) => {
console.log(err);
});