vue3 封装 toast组件

使用vue3封装 土司提示组件

<template>
  <div class="toast-wrap">
    <div v-if="mask" class="mask"></div>
    <div class="toast" ref="toast" :style="style"> {{ title }}</div>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
defineProps({
  title: { type: String },
  mask: { type: Boolean }
})
const toast = ref(null)
const style = reactive({ marginLeft: '0px' })
onMounted(() => {
  style.marginLeft = toast.value.clientWidth / 2 * -1 + 'px'
})

</script>
<style lang="less" scoped>
.toast-wrap {

  .mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 3001;

  }

  .toast {
    position: fixed;
    top: 30%;
    left: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    max-width: 400px;
    min-width: 200px;
    color: #ffffff;
    font-size: 28px;
    line-height: 34px;
    text-align: center;
    border-radius: 10px;
    padding: 20px;
    background: rgba(0, 0, 0, 0.7);
    box-sizing: border-box;
    z-index: 3000;
  }
}
</style>
import { createApp } from 'vue'
import Toast from './Toast.vue'
export default {
  instance: null,
  parent: document.createElement('div'),
  showToast ({ title, duration = 2000, mask = false }) {
    if (this.instance !== null) this.clear()
    this.instance = createApp(Toast, { title: title.toString(), mask })
    document.body.appendChild(this.parent)
    this.instance.mount(this.parent)
    setTimeout(() => {
      this.clear()
    }, duration)
  },
  hideToast () {
  this.clear()
  },
   clear () {
    if (this.instance !== null) {
      this.instance.unmount(this.parent)
      document.body.removeChild(this.parent)
      this.instance = null
    }
  },
}

//使用
import * as utils from './index.js'
utils.showToast({tiele:"标题"})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值