VUE 自定义插件Toast

记录自己遇到的问题,以备查询。

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)
发布了12 篇原创文章 · 获赞 0 · 访问量 3244

猜你喜欢

转载自blog.csdn.net/qq_28077333/article/details/88976463