手撸一个VUE toast全局可安装组件

安装vue vue elementUi

不用elementui 可自定下载iconfont来替换图标

预览

在这里插入图片描述

懂VUE的都懂 再次不赘述

代码结构

src/main.vue
<template>
  <div v-show="show" class="biztoast">
    <div class="toast_container">
      <i :class="iconClass"></i>
      <div class="toast-text">{{message}}</div>
    </div>
  </div>
</template>
<script>
const TYPE_CLASSES_MAP = {
  success: "el-icon-success",
  warning: "el-icon-warning",
  error: "el-icon-error",
  loading: "el-icon-loading"
};
export default {
  props: {
    show: Boolean,
    message: {
      type: String,
      default: "加载中"
    },
    type: {
      type: String,
      default: "loading"
    }
  },
  computed: {
    iconClass() {
      return TYPE_CLASSES_MAP[this.type] || "el-icon-loading";
    }
  }
};
</script>
<style scoped lang="scss">
.biztoast {
  width: 100%;
  .toast_container {
    background: rgba($color: #000000, $alpha: 0.8);
    border-radius: 8px;
    color: #fff;
    position: fixed;
    width: 100px;
    height: 100px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 2020;
    text-align: center;
    [class^="el-icon-"] {
      line-height: 65px;
      font-size: 30px;
    }
    .toast-text {
      font-size: 16px;
    }
  }
}
</style>
index.js
import Vue from 'vue'
import toastComponent from './src/main'

let instance;

const ToastConstructor = Vue.extend(toastComponent)

instance = new ToastConstructor({
  el: document.createElement("div")
})

instance.show = false;

const bizToast = {
  show(options = {}) {
    instance.show = true;
    if (options) {
      instance.message = typeof options === 'string' ? options : options.message;
      instance.type = options.type;
      document.body.appendChild(instance.$el);
      if(options.type != 'loading'){ //结果态 2S后销毁
        setTimeout(() => {
          this.hide()
        }, 2000);
      }
    }
  },
  hide() {
    instance.show = false;
    if (instance.$el) {
      document.body.removeChild(instance.$el)
    }
  }
}

export default {
  install() {
    if (!Vue.$biztoast) {
      Vue.$biztoast = bizToast
    }
    Vue.mixin({
      created() {
        this.$biztoast = Vue.$biztoast
      }
    })
  }
}

组件安装

import Vue from 'vue'
import bizToast from '@/components/bizToast';
Vue.use(bizToast)

组件调用

//loading 非loading态会在2S内自动关闭清除组件
this.$biztoast.show({ message: "加载中", type: "loading" });
//success 
this.$biztoast.show({ message: "加载完成", type: "success" });
//...
//关闭
this.$biztoast.hide();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值