首先需要写一个弹窗组件 Snackbars.vue
<template>
<transition name="fade" @after-leave="destroy">
<div class="text-center"
v-show="isVisable">
{{ message }}
</div>
</transition>
</template>
<script setup lang="ts">
const props = defineProps({
color:{
type: String,
default: "red"
},
message:{
type: String,
default: "affff"
},
duration:{
type: Number,
default: 500
},
destroy: Function
})
const isVisable = ref(false);
onMounted(()=> {
isVisable.value =true
setTimeout(()=>{
isVisable.value = false
}, props.duration)
})
</script>
<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
transition: all 0.5s;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
transform: translate3d(-50%, -100%);
}
.text-center{
display: flex;
position: fixed;
top: 60%;
right: 0px;
border: 1px solid #000;
background: v-bind('props.color'); // 绑定传参颜色
z-index: 999;
}
</style>
第二步 渲染组件,写一个ts文件:showTips.ts
import { h, render } from 'vue';
import Snackbar from "./Snackbars.vue";
export const showTips = {
success:(message:String, duration=5000, color="#4CAF50")=>{
showTips.create(message, duration, color)
},
error:(message:String, duration=5000, color="D32F2F")=>{
showTips.create(message, duration, color)
},
warn:(message:String, duration=5000, color="F57C00")=>{
showTips.create(message, duration, color)
},
create:(message:String, duration:Number, color:String)=>{
const handleDestroy = () => {
render(null, document.body)
}
// 使用 h 函数创建 vnode
const vnode = h(Snackbar, {
message,
color,
duration,
destroy: handleDestroy
})
// 使用 render 函数将 vnode 渲染为真实DOM并挂载到 body 上
render(vnode, document.body)
}
}
第三步在其他组件引用的时候导入
import {showTips} from '@/components/Snackbars/showTips'
showTips.success("Change successful")