必看 element ui 框架 confirm弹窗二次封装

3,155 阅读1分钟

在开发项目中过程中发现,用到很多次confirm弹窗,如是就想能不能把他封装一下,这样用起来是让组内成员更方便一点。有了这个想法就开始封装了。下面讲一下我封装的思路

首先在 umlib.js 工具函数库 定义一个方法

这里我封装的思路是一共传四个参数,titleMsg标题参数,callback回调参数,successMsg成功提示语参数, errorMsg失败提示语参数,但是这里面必传二个参数就是参数一和参数二,参数三和参数非必传,因为在一个callback参数里面也可以提示的

Vue.prototype.confirm = function (titleMsg , callback , successMsg , errorMsg = "已取消") {

      Vue.prototype.$confirm(titleMsg , "提示" , {

        confirmButtonText"确定",

        cancelButtonText"取消",

        type"warning",

      }).then(()=>{

        callback();

        if(successMsg){

          Vue.prototype.$message({

            type"success",

            message: successMsg,

          });

        }

      }).catch(()=>{

        if(errorMsg){

          Vue.prototype.$message({

            type"info",

            message: errorMsg,

          });

        }

      })

    }

页面上的实际用法

1、简写用法

没有复杂的逻辑,就可以一行代码解决

this.confirm('确定注销并退出系统吗?',() => this.$store.dispatch('LogOut'))

2、一般用法

就是在callback回调参数里面做一个简单的判断

this.confirm("是否取消?",() => {

        if (this.crowdOriented) {

          this.$router.push(`/a/b/${ this.crowdOriented }`);

        } else {

          this.$router.push("/a/b/");

        }

      },"","")

3、异步接口请求

是要异步接口请求成功之后,在执行下面的方法,

this.confirm('确定删除该条数据吗?',async () => {

        let res = await 接口(row.id)

        if(res.code == "200"){

          this.$message.success("已删除");

          this.getList();

        }

      },"","已取消")

4、同步接口请求

就是用于新增,修改同一个页面,共用一个方法的例子

this.confirm("确认保存当前数据?",() => {

            if (this.form.id != null) {

              接口 (this.form).then((response) => {

                this.msgSuccess("修改成功");

                this.$router.push("");

              });

            } else {

              addLibrary(this.form).then((response) => {

                this.msgSuccess("新增成功");

                this.$router.push("/dtTalent/Library");

              });

            }

          },"","")