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后消失
posted @ 2021-10-31 16:58  青柠i  阅读(199)  评论(0编辑  收藏  举报