VUE組件 之 Toast (Vue.extend 方式)


一、效果圖

 

二、說明

這類提示框組件我們通常都會直接在 JS 代碼中進行調用。像下面這樣:

this.$toast('別點啦,到頭啦!')

 

但看到網上大多數還是通過 component  方式實現的,這樣的話我們在使用的時候還要在 DOM 中放置一個組件元素,然后通過一個變量來控制它的顯示隱藏,這樣使用起來非常的不方便。那么有什么方法可以不用在 DOM 中手動放置組件元素就可以直接調用呢?答案就是 Vue.extend。通過 Vue.extend 方式實現的組件,需要兩個文件,一個是 .vue 文件,另外一個就是管理 .vue 的 .js  文件。具體代碼如下:

 

三、代碼

Toast.vue 文件代碼

<template>
  <div class="toast" v-show="visible">
    {{ message }}
  </div>
</template>

<script>
export default {
  name: 'toast',
  data () {
    return {
      message: '', // 消息文字
      duration: 3000, // 顯示時長,毫秒
      closed: false, // 用來判斷消息框是否關閉
      timer: null, // 計時器
      visible: false // 是否顯示
    }
  },
  mounted () {
    this.startTimer()
  },
  watch: {
    closed (newVal) {
      if (newVal) {
        this.visible = false
        this.destroyElement()
      }
    }
  },
  methods: {
    destroyElement () {
      this.$destroy()
      this.$el.parentNode.removeChild(this.$el)
    },
    startTimer () {
      this.timer = setTimeout(() => {
        if (!this.closed) {
          this.closed = true
          clearTimeout(this.timer)
        }
      }, this.duration)
    }
  }
}
</script>

<style lang="scss" scoped>
.toast {
  position: fixed;
  bottom: 15vh;
  left: 28vw;
  min-width: 40vw;
  max-width: 100vw;
  font-size: 26px;
  text-align: center;
  padding: 10px 2vw;
  border-radius: 40px;
  background-color: rgba(0, 0, 0 , 0.6);
  color: rgb(223, 219, 219);
  letter-spacing: 3px;
}
</style>

 

Toast.js 文件代碼

import Vue from 'vue'
import Toast from '@/components/layer/Toast.vue'

let ToastConstructor = Vue.extend(Toast) // 構造函數
let instance // 實例對象
let seed = 1 // 計數

const ToastDialog = (options = {}) => {
  if (typeof options === 'string') {
    options = {
      message: options
    }
  }
  let id = `toast_${seed++}`
  instance = new ToastConstructor({
    data: options
  })
  instance.id = id
  instance.vm = instance.$mount()
  document.body.appendChild(instance.vm.$el)
  instance.vm.visible = true
  instance.dom = instance.vm.$el
  instance.dom.style.zIndex = 999 + seed
  return instance.vm
}

export default ToastDialog

 

四、使用

首先在 main.js 中引入 Toast.js 並掛載到vue原型上,如下圖:

 

其次,在代碼中使用

this.$toast('別點啦,到頭啦!')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM