創(chuàng)建自定義彈窗掛載在body上
1.創(chuàng)建方法
// toast.js
import Vue from "vue";
// 創(chuàng)建函數(shù)接收要?jiǎng)?chuàng)建組件定義
function create(Component, props) {
// 創(chuàng)建一個(gè)Vue新實(shí)例
const vm = new Vue({
render(h) {
// render函數(shù)將傳入組件配置對(duì)象轉(zhuǎn)換為虛擬dom
// console.log(h(Component, { props }));
return h(Component, { props });
}
}).$mount(); //執(zhí)行掛載函數(shù)扫俺,但未指定掛載目標(biāo),表示只執(zhí)行初始化工作
// 將生成dom元素追加至body
document.body.appendChild(vm.$el);
// 給組件實(shí)例添加銷毀方法
const comp = vm.$children[0];
comp.remove = () => {
document.body.removeChild(vm.$el);
vm.$destroy();
};
return comp;
}
// 暴露調(diào)用接口
export default create;
2.組件
//notice.vue
<template>
<div class="box" v-if="isShow">
<h3>{{title}}</h3>
<p class="box-content">{{message}}</p>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: ""
},
message: {
type: String,
default: ""
},
duration: {
type: Number,
default: 1000
}
},
data() {
return {
isShow: false
};
},
methods: {
show() {
this.isShow = true;
setTimeout(this.hide, this.duration);
},
hide() {
this.isShow = false;
this.remove();
}
}
};
</script>
<style>
.box {
position: fixed;
width: 100%;
top: 16px;
left: 0;
text-align: center;
pointer-events: none;
background-color: #fff;
border: grey 3px solid;
box-sizing: border-box;
}
.box-content {
width: 200px;
margin: 10px auto;
font-size: 14px;
padding: 8px 16px;
background: #fff;
border-radius: 3px;
margin-bottom: 8px;
}
</style>
3.然后在需要的時(shí)候調(diào)用
import toast from '@/util/createToast'
import Notice from '@/components/notice'
toast (Notice, {
title: "提示",
message: flag ? "請(qǐng)求登錄!" : "校驗(yàn)失敗!",
duration: 1000
}).show()