Toast of VUE components (VUE. Extend mode)

Posted by deeem on Sun, 19 Apr 2020 16:36:28 +0200

1, Renderings

 

Two, explain

Such prompt box components are usually called directly in JS code. Like this:

this.$toast('Stop it, it's over!')

 

However, most of the Internet is implemented by component. In this way, we need to place a component element in the DOM when we use it, and then control its display and hiding through a variable. This is very inconvenient to use. So what method can be called directly without manually placing component elements in the DOM? The answer is Vue. Extend. There are two files needed for the component implemented by Vue.extend. One is the. Vue file, and the other is the. js file that manages the. Vue. The specific code is as follows:

 

Three, code

Toast.vue file code

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

<script>
export default {
  name: 'toast',
  data () {
    return {
      message: '', // message text
      duration: 3000, // Display time, MS
      closed: false, // Used to determine whether the message box is closed
      timer: null, // timer
      visible: false // Whether to display
    }
  },
  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 file code

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

let ToastConstructor = Vue.extend(Toast) // Constructor
let instance // Instance object
let seed = 1 // count

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

 

Four, use

First, introduce Toast.js in main.js and mount it on the vue prototype, as shown in the following figure:

 

Second, use in your code

this.$toast('Stop it, it's over!')

Topics: Vue