vue2封装弹框全局组件,通过函数调用
1.前提
在项目开发中,经常会使用到弹框功能,如果直接在页面中注册使用,则需要在每个页面添加标签,通过if进行显示隐藏,增加冗余代码。可以通过注册全局组件,使用函数调用的方式规避该问题。
2.弹框组件模块
2.1 创建组件模块
Prompt/index.vue
<template>
<div
class="Prompt"
:class="animationShow ? 'animationShow' : 'animationConceal'"
>
<div class="PromptText">{{ PromptText }}</div>
</div>
</template>
<script>
export default {
props: {},
data() {
return {
PromptText: "",
animationShow: false,
time: 2000,
};
},
mounted() {},
created() {
setTimeout(() => {
this.animationShow = false;
}, this.time);
setTimeout(() => {
this.$el.parentNode.removeChild(this.$el);
}, this.time + 400);
},
methods: {
},
};
</script>
<style>
@keyframes Show {
0% {
opacity: 0;
}
25% {
opacity: 0.25;
}
50% {
opacity: 0.5;
}
100% {
opacity: 1;
}
}
@keyframes Conceal {
0% {
opacity: 1;
}
25% {
opacity: 0.5;
}
50% {
opacity: 0.25;
}
100% {
opacity: 0;
}
}
.animationShow {
animation: Show 0.5s;
-moz-animation: Show 0.5s; /* Firefox */
-webkit-animation: Show 0.5s; /* Safari 和 Chrome */
-o-animation: Show 0.5s; /* Opera */
}
.animationConceal {
animation: Conceal 0.5s;
-moz-animation: Conceal 0.5s; /* Firefox */
-webkit-animation: Conceal 0.5s; /* Safari 和 Chrome */
-o-animation: Conceal 0.5s; /* Opera */
}
.Prompt {
box-sizing: border-box;
padding: 0 129px;
min-width: 400px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 0.1667rem;
font-family: PingFangSC-Semibold, PingFang SC;
font-weight: 600;
color: #000000;
line-height: 146px;
background: #ffffff;
box-shadow: 0px 2px 9px 0px rgba(207, 207, 207, 0.5);
border-radius: 14px;
opacity: 0.96;
border: 1px solid #d4d4d4;
text-align: center;
}
</style>
2.2 index.js
使用Vue.extend创建一个子类,通过new 创建实例,可以传入组件的属性,用于结合data、methods等
通过instance.
m
o
u
n
t
(
)
.
mount().
mount().el 获取到组件实际dom,最后挂载给body。
import Vue from "vue";
import Prompt from "./index.vue";
let PromptConstructor = Vue.extend(Prompt);
let instance;
const PromptTip = function(options = {}) {
instance = new PromptConstructor({
data: options,
});
document.body.appendChild(instance.$mount().$el);
};
export default PromptTip;
2.3 main.js
//mian.js
import EditionTip from '@/common/editionTip/index.js' // 路径
Vue.prototype.$EditionTip = EditionTip
2.4 使用
this.$PromptTip({
PromptText: "此处展示弹框文本,
animationShow: true,
time: 2000,
});
引用