弹窗组件,此处以element为实例,需自行修改
//dialog.vue
<template>
<el-dialog
:title="title"
:visible.sync="dialogVisible"
width="30%">
<span>{{content}}</span>
<template #footer>
<span class="dialog-footer">
<el-button @click="cancel">取消</el-button>
<el-button type="primary" @click="confirm">确定</el-button>
</span>
</template>
</el-dialog>
</template>
<script >
export default {
data () {
return {
dialogVisible: false,
title: '',
content: '',
cancelFn() {
},
confirmFn() {
}
}
},
methods: {
show(e){
this.title = e.title
this.content = e.content
this.cancelFn = e.cancel
this.confirmFn = e.confirm
this.dialogVisible = true
},
hide(){
this.dialogVisible = false
},
cancel () {
this.cancelFn()
},
confirm () {
this.confirmFn()
}
}
}
</script>
js工具
//dialog.js
import Vue from 'vue'
//组件路径
import dialog from '@/components/dialog.vue';
// 创建Dialog实例
const dialogConstructor = Vue.extend(dialog );
const dialogInstance = new dialogConstructor({
el: document.createElement('div')
});
// 将dialog元素添加到body
document.body.appendChild(dialogInstance.$el);
// 在Vue原型上添加显示和隐藏Dialog的方法
Vue.prototype.$showDialog = dialogInstance.show;
Vue.prototype.$hideDialog = dialogInstance.hide;
main.js全局引入
//dialog.js路径
import '@/utils/dialog'
使用
login(){
this.$showDialog({
title: '信息',
content: '登录成功!',
confirm () {
console.log('confirm')
this.$hideDialog()
},
cancel () {
console.log('cancel')
this.$hideDialog()
}
})
}
效果