基于element ui 和vue事件总线封装dialog函数
第一步: 创建子类并构建dialog函数
在dialog.vue中
// dialog.vue
<template>
<el-dialog :title="title" :visible.sync="dialogFormVisible" v-if="dialogFormVisible">
<component :is="componentId"></component>
</el-dialog>
</template>
<script>
export default {
props: {
title: String,
},
data() {
return {
dialogFormVisible: true,
componentId: null,
};
},
methods: {
},
};
</script>
在同级目录的index.js文件中引入dialog.vue 使用Vue.extend创建一个子类。
// index.js
import Vue from 'vue';
import Dialog from './dialog.vue'
const Instance = Vue.extend(Dialog)
export default function (componentId, prop, callback) {
return new Promise((res, rej) => {
if (!(componentId instanceof Object)) return;
let div = document.createElement("div");
div.setAttribute("id", "dialog");
document.body.appendChild(div);
new Instance({
props: {
title: {
type: String,
default: prop.title
}
},
data() {
return {
componentId
}
},
created() {
this.$EventBus.$on('dialog-destroy', (value) => {
res(value)
this.dialogFormVisible = false;
});
},
}).$mount('#dialog');
})
}
接下来,在main.js 中把dialog函数绑定在Vue的原型上,使其全局可用。
//main.js
import dialog from './components/dialog/index'
Vue.prototype.$dialog = dialog;
另外,全局的事件总线也许在此处绑定到Vue的原型上。
//main.js
Vue.prototype.$EventBus = new Vue();
第二步:数据通信处理
在utils文件夹下新建dialogClass.js文件。其类中destroy方法用于关闭弹框并传递数据。
// dialogClass.js
export default class Dialog{
constructor(vm){
this.vm = vm;
}
destroy(options){
this.vm.$EventBus.$emit('dialog-destroy',options);
}
}
vm 是实例化对象时指向Vue的实例。
第三步:使用示例
在App.vue组件中
//App.vue
<template>
<div id="app">
<button @click="onNotice">点击</button>
<button @click="open">打开</button>
</div>
</template>
<script>
import CusDiv from './components/v-model/cus-div.vue'
import example from './components/dialog/example.vue'
export default {
name: "app",
components:{CusDiv},
data() {
return {
cusValue: {
name:''
}
};
},
methods:{
onNotice(){
this.$dialog(example,{title:'提示'}).then(res=>{
console.log(res,'onNotice');
})
},
open(){
this.$dialog(example,{title:'打开'}).then(res=>{
console.log(res,'open');
});
}
}
};
</script>
使用this.$dialog(example,{title:‘打开’})方法去打开弹框。并且可以通过.then来获取数据。
方法调用中传递的参数组件
//example.vue
<template>
<div class="example">
123
<span slot="footer" class="dialog-footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="ok">确 定</el-button>
</span>
</div>
</template>
<script>
import DialogModel from "../../utils/dialogClass";
export default {
data() {
return {
model: new DialogModel(this),
};
},
methods: {
cancel() {
this.model.destroy()
},
ok() {
this.model.destroy({title:'123'});
},
},
};
</script>
这个组件中,使用DialogModel声明的实例方法去关闭弹框并传参数。