src下創(chuàng)建一個utils文件,下面放彈窗實(shí)例create.js:
//創(chuàng)建指定的組件實(shí)例并掛載到body上
import Vue from 'vue'
export default function create(Component,props){
//0.先創(chuàng)建vue實(shí)例
const vm = new Vue({
render(h) {//提供一個h函數(shù)(createElement()別名),可以渲染VNode(虛擬dom)
return h(Component,{props})
}
}).$mount();//不能直接掛在到body上,會報錯
//1.上面的vm幫我們創(chuàng)建組件實(shí)例
//2.通過$children獲取該組件的實(shí)例
const comp = vm.$children[0];
//3. 追加至body,comp是實(shí)例但不是dom,所以要用$el獲取渲染出來的dom節(jié)點(diǎn)
document.body.appendChild(comp.$el);
//4.清理函數(shù),創(chuàng)建的彈窗在關(guān)掉后需要清除,防止內(nèi)存泄露
comp.remove = () => {
document.body.removeChild(vm.$el);
vm.$destroy();
}
//5.返回組件實(shí)例
return comp;
}
components下創(chuàng)建vue文件骄蝇,簡單寫一下樣式:
<template>
<div v-if="isShow" class="model">
<h3>{{title}}</h3>
<p>{{message}}</p>
</div>
</template>
<script>
export default {
props:{
title:{
type:String,
default: ''
},
message:{
type:String,
default: ''
},
duration: {
type: Number,
default: ''
}
},
data(){
return {
isShow: false
}
},
methods:{
show(){
this.isShow = true;
setTimeout(() => {
this.hide();
}, this.duration);
},
hide(){
this.isShow = false;
this.remove();
}
}
}
</script>
<style>
.model{
width: 200px;
height: 100px;
position: fixed;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -50px;
background: #fff;
text-align: center;
border-radius: 10px;
box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.3);
}
</style>
頁面中使用:
//導(dǎo)入
import Notice from "../Notice"
import create from "@/utils/create"
//創(chuàng)建彈窗實(shí)例
let notice;
//使用的時候直接用
notice = create(Notice, {
title: 'xxx',
message: '登錄~~~',
duration: 1000
})
長這樣: