自定义弹窗组件
一、特点
(一)独立于vue实例(#app)之外的存在
(二)Js动态创建
简单案例展示
1、弹窗js
import Vue from 'vue';
export default function dialogModel(components, props) {
//创建实例
const vm = new Vue({
render(h) {
//调用外部components和props
return h(components, { props })
}
}).$mount();
//获取组件实例
const comp = vm.$children[0];
//在组件实例中新增删除事件
comp.remove = () => {
document.body.removeChild(vm.$el);
vm.$destroy();
}
//挂靠在body上
document.body.appendChild(vm.$el);
//返回组件实例
return comp;
}
2、弹窗组件
<template>
<div class="Dialog" v-if="isShow">
<h1>{{title}}</h1>
<h1>{{content}}</h1>
<button @click="closeBox">关闭</button>
<button @click="suresBox">确定</button>
</div>
</template>
<script>
export default {
inheritAttrs: false,
name: 'Dialog',
data() {
return {
isShow: false
}
},
props: {
//标题
title: String,
//内容
content: String,
返回函数
successAct: Function
},
methods: {
show() {
this.isShow = true;
},
hide() {
this.isShow = false;
this.remove();
},
closeBox() {
this.successAct('关闭');
},
suresBox() {
this.successAct('确定');
}
}
}
</script>
3、弹窗调用
<template>
<div class="Test1">
<button @click="showDia">按钮</button>
</div>
</template>
<script>
//引入弹窗组件
import Dialogs from '@/components/Dialogs'
//引入弹窗实例
import dialogModel from '@/utils/dialog.js'
export default {
name: 'Test1',
methods:{
showDia(){
//调用弹窗事件
let dia = dialogModel(Dialogs,{
title:'标题',
content:"弹框内容展示",
successAct:(res)=>{
console.log(res);
}
})
dia.show();
}
}
}
</script>