封装js (popup.js)
import Vue from 'vue'
import store from '@/store'
import router from '@/router'
const createPortal = (com, props) => {
return new Promise((resolve, reject) => {
const Ctr = Vue.extend(com)
const instance = new Ctr({
router,
propsData: {
...props
},
beforeCreate() {
this.$store = store
},
created() {
this.$once('sure', (...arg) => {
this.$destroy()
resolve(...arg)
})
this.$once('close', (...arg) => {
this.$destroy()
reject(...arg)
})
},
beforeDestroy() {
this.visible = false
this.$off('sure')
this.$off('on')
document.body.removeChild(this.$el)
}
})
instance.$mount()
document.body.appendChild(instance.$el)
})
}
export default createPortal
组件内使用
showDialog() {
// this.$popup 为 main.js引入挂在到 Vue原型的方法
this.$popup(AddDialog, { name: '王五', age: '18' }).then((res) => { // 第一个参数为组件名,第二个参数为传入组件的props<Object>
console.log(res, 'suresure') // this.$emit('sure') 进入的回调 一半用来调用刷新页面的接口
}).catch((err) => {
console.log('cancelcancel', err) // this.$emit('close') 的回调
})
},
弹窗组件
<template>
<el-dialog
:visible.sync="dialogVisible"
title="testDialog"
width="50%"
>
<div>
{{ name }} -- {{ age }}
<el-button type="primary" @click="confirm">确认</el-button>
<el-button @click="cancel">取消</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
name: '',
components: {},
props: {
name: {
type: String,
default: ''
},
age: {
type: String,
default: ''
}
},
data() {
return {
dialogVisible:true
}
},
created() {
do...
},
methods: {
confirm() {
this.$emit('sure', { test: '666' }) // 第一个参数sure与close为封装的方法,所以固定名称,第二个参数可以回传给父组件
},
cancel() {
this.$emit('close', { name: '1s' })
}
}
}
</script>
<style scoped>
</style>
网友评论