vue 定义全局方法打开弹窗

这篇博客介绍了如何在Vue中创建一个可复用的dialog组件,利用typescript进行类型定义,实现了动态传入标题和内容,并通过Promise处理确认和取消操作。该组件具有自定义样式和灵活的回调功能,可以方便地在项目中全局引用或绑定到Vue实例上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、dialog.vue

<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    class="dialog-component"
    append-to-body
    width="360px"
    top="35%"
    :show-close="false"
    @close="close"
  >
    <div class="dialog-body">
      <el-input v-model="text" ></el-input>
    </div>
    <div slot="footer" class="counter-dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="confirmFn">确定</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
@Component({
  components: {}
})
export default class DialogComponent extends Vue {
  title = "提示";
  text = "";
  private dialogVisible = true;
  callback: any = null; // 声明变量后,在 dialog.ts 中重新复制
  close() {
    this.dialogVisible = false;
    this.callback({ action: "cancel", data: null });
  }
  confirmFn() {
    this.callback({ action: "confirm", data: this.text });
    this.dialogVisible = false;
  }
}
</script>

<style lang="scss">
.dialog-component {
  text-align: left;
  padding: 20px;
  padding-top: 15vh;
  .dialog-body {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>

2、dialog.ts

import Vue from "vue";
import CounterDialog from "./dialog.vue";

// 创建基于 CounterDialog 类的构造函数
const DialogConstructor = Vue.extend(CounterDialog);

/**
 * @param obj 设置默认的 data 数据
 * @returns 
 */
export const showDialogFn = (obj: any) => {
  return new Promise((resolve, reject) => {
    const dialogDom = new DialogConstructor({
      el: document.createElement("template"),
      data() {
        return {
          ...obj
        };
      }
    });
    // 改写回调函数,完成 promise 的状态修改
    dialogDom.callback = ({ action, data }) => {
      if (action === "confirm") {
        resolve(data);
      } else if (action === "cancel") {
        reject(data);
      }
    };
    document.body.appendChild(dialogDom.$el);
  });
};

3、引用或绑定全局

import Vue from "vue";
import { showDialogFn } from "./dialog.ts"
// 通过函数的方法打开弹窗
showDialogFn({
    text: "初始值",
    title: "说明"
}).then(res => {
console.log("res", res)
})

// 绑定到 vue 实例上
Vue.prototype.$showDialogFn = showDialogFn;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值