Custom Toast plugin in Vue

created at 11-15-2021 views: 8

The Toast component is used to display prompt information, which can be used in the whole project.

1. Toast.vue

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

<script>
export default {
  name: "Toast",
  data() {
    return {
      message: "",
      isShow: false,
    };
  },
  methods: {
    show(msg, delay = 2000) {
      this.message = msg;
      this.isShow = true;
      setTimeout(() => {
        this.message = "";
        this.isShow = false;
      }, delay);
    },
  },
};
</script>

<style scoped>
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 10px 12px;
  z-index: 10;

  color: #fff;
  background: rgba(0, 0, 0, 0.7);
}
</style>

2. Register the plugin

/**
  * Custom plug-in Toast message prompt box
  * index.js, in the same folder as the Toast component
  */
import Toast from "./Toast.vue"
const obj = {};

obj.install = function (Vue) {
   // 1. Create a component builder
   const toastConstructor = Vue.extend(Toast);

   // 2. new, create a component object
   const toast = new toastConstructor();

   // 3. Manually mount to an element
   toast.$mount(document.createElement("div"));

   // 4. toast.$el has corresponding elements
   document.body.appendChild(toast.$el);

   // Mount to vue
   Vue.prototype.$toast = toast;
}

export default obj;

3. Use in main.js

// Import custom plugin Toast
import toast from "@/components/common/toast/index.js"

// Use custom plugin toast
Vue.use(toast);

4. Used in components

this.$toast.show("xxxxxx"); // The message box shows xxxxx, which disappears after 2s by default

this.$toast.show("xxxxxx!", 3000);// The message box shows xxxxx and disappears after 3s
created at:11-15-2021
edited at: 11-15-2021: