Vue自定義全局Toast組件

背景:

在前端項(xiàng)目開發(fā)中,我們除了日常使用的vant庫,還經(jīng)常會根據(jù)業(yè)務(wù)自己去封裝一些組件庫。這樣即會使得我們的代碼可復(fù)用,又提高了我們的開發(fā)效率。

以最簡化的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: '網(wǎng)絡(luò)錯(cuò)誤',
  duration: 1000
})

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

備注

基于上面最簡化的demo,我們可以再豐富此組件亦可創(chuàng)造其他組件。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 有時(shí)候我們在做開發(fā)的時(shí)候,就想自己寫一個(gè)插件然后就可以使用自己的插件,那種成就感很強(qiáng)。博主最近研究element-...
    前小白閱讀 781評論 0 0
  • 經(jīng)常的,業(yè)務(wù)中需要用到一些全局的組件,類似Toast、彈窗等,如果我們在每個(gè)頁面都單獨(dú)的去引入的話,就會比較麻煩,...
    陳成熟閱讀 565評論 0 5
  • 首先創(chuàng)建一個(gè)項(xiàng)目 定義組件文件夾 在項(xiàng)目src目錄下新建文件夾components用于存放所有的自定義組件,接著在...
    帥帥噠主公閱讀 5,219評論 0 0
  • 自定義vue全局組件use使用(解釋vue.use()的原理) 我們在前面學(xué)習(xí)到是用別人的組件:Vue.use(V...
    tengrl閱讀 2,593評論 0 0
  • 首先在自己的項(xiàng)目路徑的組件目錄components下創(chuàng)建pagination文件夾,我已分頁組件為例,pagina...
    level閱讀 480評論 0 1

友情鏈接更多精彩內(nèi)容