美文网首页vue
vue中二次封装elementUi的弹出框MessageBox

vue中二次封装elementUi的弹出框MessageBox

作者: L黑洞 | 来源:发表于2020-03-18 18:30 被阅读0次
这样的确认弹出框 在后台很多地方都要用到 当点击确认的时候去执行自己的操作 它本身的代码也是很大一坨, 所以需要我们对它进行二次封装 直接上图!!!
1. 当点击页面的发送按钮 触发弹框
2. 调用我封装好的 confirm({})
  • 这个函数{}大括号是我要传的参数 confirm()这个函数会返回promise对象 当你点击确认是会resolve()回来,然后就可以在then()方法里写你要执行的代码
// 这是为了让你们看我在哪里定写的这个方法
import { confirm } from '@/utils/index'
//发送函数
handleSend(row){
          confirm({
                content: `你确定要将轮播图发送到<b>${this.openType(row.data.openType)}</b>吗?`
            }).then(()=> {
                //这是一个btn loding 
                this.$set(row.data, '$loading', true)
                // 测试一下
                setTimeout(() => {
                    this.$set(row.data, '$loading', false)
                    this.$message({ type: 'success', message: '发送成功!' });
                },2000)
                // 请求体
                // sendBanner().then(res => {
                //     console.log(res)
                //     if(res.data.status === 200){
                //         // 这就是你成功后写的代码片段
                //         console.log('ss')
                //     }
                // })
            })
        },
3. 这个函数我写在utils下的index.js
import Vue from 'vue'
const vm = new Vue()
/**
* element-ui confirm 二次封装
* @param {Object} param
* @returns {Object} Promise 点击了确认resolve() 
*/
export function confirm(param) {
    // 默认参数
    let config = {
        tip: '提示',
        content: '你确定要执行此操作么吗?',
        btn: { confirm: '确定', cancel: '取消', },
        type: 'warning'
    }
    // 如果有参数传入并且长度大于0 则替换原来的指定默认配置 
    if (param && Object.keys(param).length) {
        for (let item in param) {
            config[item] = param[item]
        }
    }
    return new Promise((resolve) => {
        vm.$confirm(config.content, config.tip, {
            confirmButtonText: config.btn.confirm,
            cancelButtonText: config.btn.cancel,
            type: config.type,
            dangerouslyUseHTMLString: true
        }).then(() => {
            resolve()
        }).catch(() => {
            vm.$message({ type: 'info', message: '已取消' })
        })
    })
}

我的封装也不一定是最好的, 但是目前还是比较适合我的业务的,后续遇到问题的话,再继续优化吧! 加油~ 奥里干

相关文章

网友评论

    本文标题:vue中二次封装elementUi的弹出框MessageBox

    本文链接:https://www.haomeiwen.com/subject/oetcyhtx.html