Vue2 进阶:创建支持 await 的自定义 $confirm 方法

202 阅读1分钟

在 Vue 2 中,你可以通过扩展 Vue 的原型(prototype)或者在你的 Vue 实例中创建一个方法来封装自定义的 $confirm 函数,并且使其支持 await。由于 Element UI 的 $confirm 方法不直接返回一个 Promise,你需要自己封装一个 Promise。

以下是如何在 Vue 2 中封装一个自定义的 $confirm 方法,使其支持 await 的示例:

  1. 全局扩展 Vue 原型

在你的 main.js 或类似的入口文件中,你可以全局扩展 Vue 的原型:

import Vue from 'vue';  
import ElementUI from 'element-ui';  
import 'element-ui/lib/theme-chalk/index.css';  
  
Vue.use(ElementUI);  
  
// 封装自定义的 $confirm 方法  
Vue.prototype.$myConfirm = function (message, title = '提示', options = {}) {  
  return new Promise((resolve, reject) => {  
    this.$confirm(message, title, {  
      ...options,  
      confirmButtonText: '确定',  
      cancelButtonText: '取消',  
      type: 'warning',  
      center: true,  
      beforeClose: (action, instance, done) => {  
        // 在这里你可以添加一些在关闭前执行的逻辑  
        done();  
      }  
    }).then(() => {  
      // 用户点击了确定按钮  
      resolve();  
    }).catch(() => {  
      // 用户点击了取消按钮或关闭了对话框  
      reject();  
    });  
  });  
};
  1. 在组件中使用

现在你可以在你的 Vue 组件中使用 $myConfirm 方法了,并且可以使用 await 来等待用户的选择:

export default {  
    methods: {  
      async doSomethingWithConfirmation() {  
        try {  
          await this.$myConfirm('你确定要继续吗?');  
          // 用户点击了确定按钮,执行你的逻辑  
          console.log('用户已确认,执行后续操作...');  
        } catch (error) {  
          // 用户点击了取消按钮或关闭了对话框  
          console.log('用户已取消操作...');  
        }  
      }  
    }  
  };
  1. 注意事项
  • 在全局扩展 Vue 原型时要小心,因为这会影响到所有的 Vue 实例。如果你只想在特定的 Vue 实例中使用,那么可以在该实例的选项中定义一个方法,而不是扩展原型。
  • 当你使用 await 时,确保你的函数被标记为 async
  • 在 beforeClose 回调中,你可以添加一些在对话框关闭前执行的逻辑。在这个例子中,我只是简单地调用了 done() 来继续关闭对话框的过程。