vue 之 Toast插件的封装

在这里插入图片描述
在这里插入图片描述

vue 之 Toast插件的封装

toast/toast.vue

<!-- toast组件  -->
<template>
  <div class="toast" :style="toastClass" v-show="isShowToast">{{ message }}</div>
</template>

<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      message: "",
      isShowToast: false,
      type: "success"
    };
  },
  computed: {
    toastClass() {
      return this.type === "success" ? { color: "green" } : { color: "red" };
    }
  },
  methods: {
    show(message, duration = 1000, type = "success") {
      this.isShowToast = true;
      this.message = message;
      this.type = type;
      console.log("toast", this.type);
      setTimeout(() => {
        this.isShowToast = false;
      }, duration);
    }
  }
};
</script>
<style  lang="scss" scoped>
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 10px;
  color: #fff;
  background: rgba(150, 200, 112, 0.75);
  z-index: 999;
}
</style>

toast/index.js

  • toast插件的创建
import Toast from './toast.vue';
const obj = {}
obj.install = function (Vue) {
	// 1:创建一个组件构造器 传入组件对象
	const toastContrustor = Vue.extend(Toast);
	// 2:使用new方式,根据组件构造器,可以创建出来一个组件对象
	const toast = new toastContrustor();
	// 3:将组件对象,手动的挂载到某一个元素身上
	toast.$mount(document.createElement('div'));
	// 4:toast.$el对应的就是div了 然后把这个对象添加到body之中!
	document.body.appendChild(toast.$el);

	Vue.prototype.$toast = toast;
}
export default obj;

main.js

toast插件的安装

import Toast from './components/toast/index';
//安装toast插件
Vue.use(Toast);

home.vue

toast插件的使用

<!--  -->
<template>
  <div class="video-container">
    视频
    <button @click="showToast">显示toast</button>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {};
  },
  methods: {
    showToast() {
      this.$toast.show("我是成功的", 1000);
      // this.$toast.show("我是失败的", 1000, "fail");
    }
  },
};
</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值