vue3【组件封装】消息提示 Toast

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)
相关推荐
无法长大3 小时前
如何判断项目需不需要用、能不能用Tailwind CSS
前端·css·vue.js·elementui·vue3·tailwind css
cui_win1 天前
企业级中后台开源解决方案汇总
开源·vue3·ts
Sapphire~2 天前
Vue3-19 hooks 前端数据和方法的封装
前端·vue3
記億揺晃着的那天2 天前
Vue3 动态路由在生产环境才出现白屏的排查与解决(keep-alive 踩坑实录)
vue3·vue router·动态路由·生产环境报错
kong79069286 天前
Vue3快速入门
前端·vue3
无法长大7 天前
Mac M1 环境下使用 Rust Tauri 将 Vue3 项目打包成 APK 完整指南
android·前端·macos·rust·vue3·tauri·打包apk
淡笑沐白8 天前
Vue3使用ElementPlus实现菜单的无限递归
javascript·vue3·elementplus
Sapphire~8 天前
Vue3-18 生命周期(vue2+vue3)
vue3
Sapphire~9 天前
Vue3-17 父子组件使用props传值
vue3
小圣贤君10 天前
在 Electron 应用中优雅接入 DeepSeek AI:从零到一的完整实践指南
人工智能·electron·vue3·ai写作·deepseek