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;