使用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:"标题"})