1、 使用Vue实例化方法
// MyDialog.js
import Vue from 'vue'
export const openFormDialog = function ({ props = {}, events = {} }) {const vm = new Vue({data () {return {form: {}}},render () {return (<el-dialogvisible={true}{...{ props }}{...{ on: events }}onClose={() => handleEvent('close')}><el-form label-width='80px'><el-form-item label='活动名称'><el-input v-model={this.form.name}></el-input></el-form-item><el-form-item label='活动区域'><el-select v-model={this.form.region} placeholder='请选择活动区域'><el-option label='区域一' value='shanghai'></el-option><el-option label='区域二' value='beijing'></el-option></el-select></el-form-item></el-form><span slot='footer' class="dialog-footer"><el-button onClick={() => { handleEvent('cancel') } }>取 消</el-button><el-button type="primary" onClick={() => handleEvent('confirm', this.form) }>确 定</el-button></span></el-dialog>)}}).$mount()const close = () => {document.body.removeChild(vm.$el)vm.$destroy()}const handleEvent = async (eventName, form) => {await events[eventName] && typeof events[eventName] === 'function' && events[eventName](form)close()}document.body.appendChild(vm.$el)
}
2、使用Vue.extend方法
// MyDialog.vue
<template><el-dialog:visible.sync="dialogVisible"v-bind="options.props"v-on="options.events"><el-form label-width='80px'><el-form-item label='活动名称'><el-input v-model="form.name"></el-input></el-form-item><el-form-item label='活动区域'><el-select v-model="form.region" placeholder='请选择活动区域'><el-option label='区域一' value='shanghai'></el-option><el-option label='区域二' value='beijing'></el-option></el-select></el-form-item></el-form><span slot="footer" class="dialog-footer"><el-button @click="dialogVisible = false">取 消</el-button><el-button type="primary" @click="onConfirm">确 定</el-button></span></el-dialog>
</template><script>
export default {data () {return {dialogVisible: true,options: {props: {width: '30%'},events: {}},form: {}}},methods: {setAttrs (options) {this.options = { ...options }},async onConfirm () {await this.options.events.confirm && typeof this.options.events.confirm === 'function' && this.options.events.confirm(this.form)this.dialogVisible = false}}
}
</script>
// MyDialog.js
import Vue from 'vue'
import Dialog from './VDialog.vue'
export const openFormDialog = function (options) {const DialogConstructor = Vue.extend(Dialog)const instance = new DialogConstructor()instance.setAttrs(options)instance.$mount()document.body.appendChild(instance.$el)
}
3、注册使用
// main.js
import { openFormDialog } from './components/MyDialog.js'
Vue.prototype.$openFormDialog = openFormDialog
// 调用方法
this.$openFormDialog({props: {title: '测试标题',width: '30%',beforeClose (done) {done()}},events: {close () {console.log('close')},cancel () {console.log('cancel')},confirm (form) {console.log(form)}}})
以上为简单例子,可根据场景进行优化,期望各位留言告知是否有更好的实现方法