src/components/Toast.vue
html
<template>
<transition name="fade">
<div class="fixed w-full h-full left-0 top-0 flex z-100 transition-all" v-if="show">
<div
:style="{ background: bgColor, color: textColor }"
:class="['m-auto px-4 py-2 rounded-2']"
>
{{ text }}
</div>
</div>
</transition>
</template>
<script setup lang="ts">
interface ToastType {
type: string
text: string
time?: number
}
const props = defineProps<ToastType>()
const type = props.type
const bgColor = ref('#edf2fc')
const textColor = ref('#aca9b7')
if (type === 'success') {
bgColor.value = '#f0f9eb'
textColor.value = '#9bcb76'
} else if (type === 'error') {
bgColor.value = '#fef0f0'
textColor.value = '#f56c93'
} else if (type === 'warning') {
bgColor.value = '#fdf6ec'
textColor.value = '#e6a23c'
}
const show = defineModel({ default: false })
watch(show, () => {
if (show.value) {
setTimeout(() => {
show.value = false
}, props.time || 2000)
}
})
</script>
使用
html
<button @click="show_msg = true">保存</button>
<teleport to="body">
<Toast v-model="show_msg" text="操作成功!" type="success"> </Toast>
</teleport>
ts
const show_msg = ref(false)