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('别点啦,到头啦!')

 

posted @ 2019-01-26 20:41  前端小玖  阅读(9649)  评论(3编辑  收藏  举报