需求说明
最近在做前端开发,发现使用vue+element组合,发现ElementUI,没有一个倒计时跳转的功能,于是自己DIY了一了,供大家参考使用。
效果如下
JS代码
function closeAlert() {
let messageBox = document.getElementsByClassName('el-message-box__wrapper')
let model = document.getElementsByClassName('v-modal')
if (messageBox) {
messageBox[0].parentNode.removeChild(messageBox[0])
model[0].parentNode.removeChild(model[0])
}
}
function changeAlert(msg) {
let messageBox = document.querySelector('.el-message-box__message>p')
if (messageBox) {
messageBox.innerHTML = msg
}
}
function alert(that, title, goFunc, countdown) {
if (!countdown) {
countdown = 3
}
const tail = ' 秒后自动跳转'
let msg = countdown + tail
changeAlert(msg)
var interval = setInterval(() => {
countdown--
msg = countdown + tail
changeAlert(msg)
if (countdown === 0) {
window.clearInterval(interval)
window.clearTimeout(timeout)
}
},1000)
const timeout = setTimeout(() => {
closeAlert()
window.clearInterval(interval)
if (goFunc) {
goFunc()
}
}, countdown * 1000)
that.$alert(msg, '提示', {
confirmButtonText: '前往',
type: 'warning',
title: title,
center: true,
showClose: false,
roundButton: true,
closeOnHashChange: true
}).then(() => {
window.clearInterval(interval)
window.clearTimeout(timeout)
if (goFunc) {
goFunc()
}
}).catch(() => {
})
changeAlert(msg)
}
export default {
alert
}
使用
this.elementUtils.alert(this, '车道被占用,请先在判级作业中完成检测。', this.goGrading, 5)
说明
- this.elementUtils这个变量是我注入到全局变量里的,大家使用的时候,直接导入使用就可以了
- this.goGrading方法就是一个router的路由跳转,替换成你自己的跳转方法
- 样式什么的,可以自己去第一个JS代码中,修改$alert中的option参数,具体参考官方文档:element.eleme.cn/#/zh-CN/com…