欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

VUE 自定义插件Toast

程序员文章站 2024-03-04 16:54:41
...

toast.js

import ToastTemplate from './ToastTemplate'

let Toast = {}

Toast.install = function(Vue,params={}){
  const VueToast = Vue.extend(ToastTemplate)  //创建模板
  let toast = null

  Vue.prototype.$toast = (params={}) =>{
    if(!toast){
      toast = new VueToast().$mount()  //创建实例
      document.body.appendChild(toast.$el)  //挂载实例
    }
    toast.show(params)

  }
}
export default Toast

ToastTemplate.vue

<template>
  <div class="msg" ref="msg" :style="{backgroundColor: backgroundColor,color: color}" v-show="isShow" v-html="message"></div>
</template>

<script>
  export default {
    name: 'ToastTemplate',
    data(){
      return{
        isShow: false,
        color: '#FFFFFF',
        backgroundColor: '#29B0F0',
        message: '333',

        time:800,
        timer:null,
        animate:null,
      }
    },
    updated(){
      let left = this.$refs.msg.clientWidth/2
      this.$refs.msg.style.left = 'calc(50% - '+ left +'px)'
    },
    methods:{
      show(params) {
        let _this = this
        if(this.animate){
          this.animate.cancel()
        }
        if(this.timer){
          clearTimeout(this.timer);
        }
        //初始化参数
        let { color,backgroundColor,message } = params
        this.color = color?color:'#FFFFFF'
        this.backgroundColor = backgroundColor?backgroundColor:'#29B0F0'
        this.message = message
        this.isShow = true

        this.timer = setTimeout(function () {
          _this.animate = _this.$refs.msg.animate([
            {opacity:1},
            {opacity:0}
          ],{duration:500})

          _this.animate.onfinish = function(){
            _this.isShow = false
            clearTimeout(_this.timer);
          }
        },_this.time)
      }
    }
  }
</script>

<style scoped>
  .msg{
    position: fixed;
    top: 38%;
    border-radius: 2px;
    padding: 5px 10px;
  }
</style>

main.js

import Toast from './Toast'
Vue.use(Toast)