vue2封装弹框全局组件,通过函数调用

文章介绍了如何在Vue2项目中封装一个弹框组件,通过函数调用来实现全局使用。首先创建Prompt组件模块,包含动画效果;然后在index.js中利用Vue.extend创建子类并挂载到body;在main.js中将弹框方法挂载到Vue原型上;最后展示了如何在页面中调用此全局方法来显示弹框。
摘要由CSDN通过智能技术生成

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,
      });

引用

链接: http://events.jianshu.io/p/5ef66a5b4127

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值