vue写一个自己的全局插件(全局toast提示)

效果:

 

 

目录:

 

 

 

 对外暴露index.js

import initShowToast from './showToast';
import initShowMsgPopup from './globalMsgPopup';

export default {
  install(Vue) {
    initShowToast(Vue);
    initShowMsgPopup(Vue);
  }
}

toast.vue

<template>
  <div class="toast" v-show="toastShow" :style="style">
    {{toastText}}
  </div>
</template>

js

<script>
  import {
    getMaxZIndex
  } from "@/utils/tools"
  export default {
    data() {
      return {
        toastShow: false,
        toastText: '',
        timmer: '',
        time: 3000,
        zIndex:0
      }
    },
    computed: {
      style() {
        return {
          zIndex: this.zIndex
        }
      },
    },
    watch: {
      toastShow(now) {
        if(now) this.startTimeout();
      }
    },
    methods: {
      startTimeout() {
        this.getZIndex();
        this.stopTimeout();
        this.timmer = setTimeout(this.hideToast, this.time);
      },
      stopTimeout() {
        clearInterval(this.timmer);
      },
      hideToast() {
        this.toastShow = false;
      },
      getZIndex() {
        this.zIndex = getMaxZIndex() + 10;
      }
    }
  }
</script>

css"

<style lang='scss' scoped>
  .toast {
    position: fixed;
    left: 50%;
    top: 45%;
    transition: all .5s;
    transform: translateX(-50%) translateY(-50%);
    color: #FFF;
    text-align: center;
    background: rgba(17, 17, 17, 0.6);
    max-width: 80%;
    min-width: 450px;
    padding: 18px 30px;
    border-radius: 25px;
  }
</style>

属于showToast的index.js

import toast from './src/toast.vue';

function install(Vue) {
  const ToastConstructor = Vue.extend(toast);
  const instance = new ToastConstructor();
  instance.$mount(document.createElement('div'));
  document.body.appendChild(instance.$el);

  Vue.prototype.$showToast = function (str,time) {
    instance.toastShow = false;
    Vue.nextTick(() => {
      instance.toastText = str;
      instance.toastShow = true;
      instance.time = time;
    })
  }
}

export default install;

页面调用:

(this as any).$showToast('提示内容', 5000);
posted @ 2020-11-17 10:47  遇你温柔如初  阅读(592)  评论(0)    收藏  举报