封装toast弹窗

js部分

import vue from "vue";
// 这里就是我们刚刚创建的那个静态组件
import toastComponent from "./toast.vue";   //把vue组件引进来

// 返回一个 扩展实例构造器
const ToastConstructor = vue.extend(toastComponent);

// 定义弹出组件的函数 接收2个参数, 要显示的文本 和 显示时间
function showToast(text, duration = 2000) {
  const toastDom = new ToastConstructor({
    el: document.createElement("div"),
    data() {
      return {
        text: text,
        showWrap: true, // 是否显示组件
        showContent: true // 作用:在隐藏组件之前,显示隐藏动画
      };
    }
  });
  document.body.appendChild(toastDom.$el);

  // 提前 250ms 执行淡出动画(因为我们再css里面设置的隐藏动画持续是250ms)
  setTimeout(() => {
    toastDom.showContent = false;
  }, duration - 1000);
  // 过了 duration 时间后隐藏整个组件
  setTimeout(() => {
    toastDom.showWrap = false;
  }, duration);
}
// 注册为全局组件的函数
function registryToast() {
  // 将组件注册到 vue 的 原型链里去,
  // 这样就可以在所有 vue 的实例里面使用 this.$toast()
  vue.prototype.$toast = showToast;
}

export default registryToast;

toast.vue部分 可以任意修改弹出时间,根据实际情况

<template>
  <div class="wrap" v-if="showWrap" :class="showContent ?'fadein':'fadeout'">{{text}}</div>
</template>
 
<style scoped>
.wrap {
  position: fixed;
  left: 50%;
  top: 50%;
  background: rgba(0, 0, 0, 0.35);
  padding: 10px;
  border-radius: 5px;
  transform: translate(-50%, -50%);
  color: #fff;
}
.fadein {
  animation: animate_in 0.1s;
}
.fadeout {
  animation: animate_out 0.1s;
  opacity: 0;
}
@keyframes animate_in {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
@keyframes animate_out {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</style>

把js文件import进main.js里,最后用Vue.prototype. t o a s t = x x x x ; 的 方 式 挂 载 到 原 型 上 , 就 可 以 直 接 在 页 面 t h i s . toast=xxxx;的方式挂载到原型上,就可以直接在页面 this. toast=xxxx;this.toast(‘我是消息’)了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值