封裝的ElementUI中confirm確認彈窗,開箱即用i👊
關於確認彈窗,項目開發中使用頻率比較高,相對於ElementUI的寫法個人覺得有點繁瑣,同樣的代碼要寫好多遍,所以對其代碼進行了封裝整理(如下)
import { MessageBox, Message } from 'element-ui'
const confirm = (text) => {
return new Promise((resolve, reject) => {
MessageBox.confirm(text, '提示', {
confirmButtonText: '確定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
resolve(true)
}).catch(() => {
Message.info('已取消')
reject(false)
})
}).catch(() => {
// 可對錯誤進行處理
})
}
export default confirm
- 如何使用呢?
直接引入調用即可,不過要注意這個方法是異步的,所以要處理好異步交互
比如在vue組件中使用
import confirm from '@/utils/confirm' // 引入
...
methods: {
async toggleStarClick(data) {
const res = await confirm('確認要取消星標嗎?')
if (res) {
...
}
}
// 或者
toggleStarClick(data) {
confirm('確認要取消星標嗎?').then(res => {
if(res) {
...
}
})
}
}