Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Wind direction, more suitable for flying

Implementation effect

Implementation steps

Start by writing a toast component

// Toast.vue
<template>
  <div id="toast" :class="[isActive ? 'active' : '', type]">
    {{ message }}
  </div>
</template>

<script>
export default {
  name: "Toast".data() {
    return {
      message: "".// The message passed
      isActive: false.// Is active (displayed on the page)
      type: "".// Message style
      timer1: null.timer2: null}; },mounted() {
    this.$nextTick(() = > {
      this.isActive = true;
    });
    this.timer1 = setTimeout(() = > {
      this.isActive = false;
    }, this.delayer);
    this.timer2 = setTimeout(() = > {
      this.$destroy(true);// Destroy the vue instance
    }, this.delayer * 2);
  },
  destroyed() {
    this.$el.parentNode.removeChild(this.$el);// Remove the DOM element
    clearTimeout(this.timer1);
    clearTimeout(this.timer2); }};</script>

<style scoped>
#toast {
  position: fixed;
  top: -50px;
  left: 50%;
  transform: translate(-50%.0);
  padding: 13px 20px;
  border-radius: 15px;
  z-index: 999;
  opacity: 0;
  transition: all 1s;
}
#toast.success {
  background-color: #f0f9eb;
  color: #67c23a;
}
#toast.error {
  background-color: #fef0f0;
  color: #f56c6c;
}
#toast.active {
  top: 30px;
  opacity: 1;
}
</style>
Copy the code

Note: Destroy the Vue instance, empty the timer, and remove dom elements after toast disappears

Encapsulate as a plug-in

// index.js
import Toast from "./Toast.vue";
const obj = {};
obj.install = function(Vue) {

  //1. Create a component constructor
  const toastContrustor = Vue.extend(Toast);
  
  Vue.prototype.$toast = function(message, type, delayer = 3000) {

    // create a component object based on the component constructor
    const toast = new toastContrustor();

    Object.assign(toast, { message, type, delayer });

    //3. Manually mount the component object to an element

    toast.$mount(document.createElement("div"));

    //4. Toast.$el = div
    document.body.appendChild(toast.$el);
  };
};

export default obj;

Copy the code
//main.js
import toast from "components/common/toast";

Vue.use(toast);
Copy the code

File structure

use

this.$toast("hi,i am spiderman"."success".5000);

this.$toast("hi,i am spiderman"."error".5000);
Copy the code

The day is always new, the future is not far away