1. 程式人生 > 其它 >Vue中自定義Toast外掛

Vue中自定義Toast外掛

Toast元件用於展示提示資訊,屬於專案全域性都可以使用。

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. 註冊外掛

/**
 * 自定義外掛 Toast 訊息提示框
 * index.js,與Toast元件在同一資料夾下
 */
import Toast from "./Toast.vue"
const obj = {};

obj.install = function (Vue) {
  // 1. 建立元件構建器
  const toastConstructor = Vue.extend(Toast);

  // 2. new ,建立元件物件
  const toast = new toastConstructor();

  // 3. 手動掛載到某一個元素上
  toast.$mount(document.createElement("div"));

  // 4. toast.$el 就有相應元素
  document.body.appendChild(toast.$el);

  // 掛載到 vue 
  Vue.prototype.$toast = toast;
}

export default obj;

3. main.js 中使用

// 匯入自定義外掛 Toast
import toast from "@/components/common/toast/index.js"

// 使用自定義外掛 toast
Vue.use(toast);

4. 元件中使用

this.$toast.show("xxxxxx");      // 訊息彈框顯示xxxxx,預設2s後消失

this.$toast.show("xxxxxx!", 3000);// 訊息彈框顯示xxxxx,3s後消失

人生人山人海人來人往,自己自尊自愛自由自在。

本文來自部落格園,作者:青檸i,轉載請註明原文連結:https://www.cnblogs.com/fuct/p/15490051.html