基于vue封装toast插件

toast.vue部分:

<template>
  <transition name="toast">
    <div class="toast" v-show="show" :class="type">
      <!-- <span class=""></span> -->
      <p>{{message}}</p>
    </div>
  </transition>
</template>

<script>
export default {
  data () {
    return {
      type: '',
      message: '',
      show: false
    }
  }
}
</script>

<style lang="scss" scoped>
.toast{
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  padding: 5px 10px;
  background-color: rgba(0,0,0,.5);
  color: #fff;
  text-align: center;
  border-radius: 4px;
  font-size: 14px;
  line-height: 18px;
}
.success{
  background-color: rgba(28,204,11,.5);
}
.error{
  background-color: rgba(255,0,18,.9);
}
.toast-enter-to,.toast-leave{
  opacity: 1;
}
.toast-enter-active,.toast-leave-active{
  transition: all ease 0.5s;
}
.toast-enter,.toast-leave-to{
  opacity: 0;
}
</style>

toast.js:

import Vue from 'vue'
import toast from '@components/toast.vue'

let Toast = Vue.extend(toast)
let instance
let timer = null // 定义定时器
let toastMsg = (options) => { // options参数,定义提示框的类型,提示文字,停留时间
  if (!instance) {
    instance = new Toast() // 创建toast实例
    document.body.append(instance.$mount().$el) // 将toast实例挂在到页面中
  }
  instance.duration = 3000 // 定义默认停留时间
  if (typeof options === 'string') {
    instance.message = options
  } else if (typeof options === 'object') {
    instance.type = options.type
    instance.message = options.message
    instance.duration = options.duration || 3000
  } else {
    return
  }
  instance.show = true
  timer = setTimeout(() => {
    instance.show = false
    clearTimeout(timer)
    timer = null
  }, instance.duration)
}

export default toastMsg

全局调用:

  main.js:

// 引入toast.js
import Toast from '@utils/toast'

// 将toast挂载到Vue原型中
Vue.prototype.$toast = Toast

其他页面使用:

methods: {
    doSome () {
      this.$toast('提交成功')
    },
    doSome2 () {
      this.$toast({
        type: 'success',  // type类型:success || error || default(默认)
        message: '提交成功',
        duration: 2000
      })
    }
}

局部调用:

 引入:

import Toast from '@utils/toast.js'

 调用:

Toast('123')
或者
Toast({
  type: 'error',
  message: '错误!',
  duration: 2000
})
发布了18 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Yw_better/article/details/103508749