Vue自定义全局Toast组件

2021-03-02  本文已影响0人  Luciena

背景:

在前端项目开发中,我们除了日常使用的vant库,还经常会根据业务自己去封装一些组件库。这样即会使得我们的代码可复用,又提高了我们的开发效率。

以最简化的Toast组件举例:

/components/toast.vue

<template lang="pug">
  .app(v-show='show')
    span {{ msg }}
</template>

<script>
export default {
  name: 'toast',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    msg: {
      type: String,
      default: '提示'
    },
    duration: {
      type: Number,
      default: 2000
    }
  },
  data: {
    timerDuration: null
  },
  watch: {
    show(n) {
      if (!n && this.timerDuration) {
        clearTimeout(this.timerDuration)
        this.timerDuration = null
      }
    }
  },
  methods: {
    init() {
      this.show = true
      this.timerDuration = setTimeout(() => {
        this.show = false
      }, this.duration)
    },
    clear() {
      this.show = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 160px;
  height: 40px;
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  span {
    display: block;
    color: #fff;
    font-size: 14px;
  }
}
</style>

/common/toast.js

import Toast from '@/components/toast.vue'
let ConfirmConstructor, instance

const showToast = {
  install(Vue) {
    ConfirmConstructor = Vue.extend(Toast)
    instance = new ConfirmConstructor().$mount()
    document.body.appendChild(instance.$el)

    Vue.prototype.$showToast = options => {
      Object.assign(instance, options)
      instance.init()
    }
    Vue.prototype.$showToast.clear = () => {
      instance.clear()
    }
  }
}

export default showToast

/main.js

import ShowToast from './common/toast'
Vue.use(ShowToast)

/views/demo.vue

// 展示toast
this.$showToast({
  msg: '网络错误',
  duration: 1000
})

// 清除toast
this.$showToast.clear()

备注

基于上面最简化的demo,我们可以再丰富此组件亦可创造其他组件。

上一篇 下一篇

猜你喜欢

热点阅读