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)
相关推荐
梵得儿SHI16 小时前
Vue 3 工程化实战:Axios 高阶封装与样式解决方案深度指南
前端·javascript·vue3·axios·样式解决方案·api请求管理·统一请求处理
叱咤少帅(少帅)1 天前
vue3 开源项目
vue3
儒雅的烤地瓜4 天前
Vue | 一文详解Vue3中的Setup()函数
vue.js·vue3·vue2·组合式api·setup函数·option api
Irene19915 天前
ElementPlus 与成熟后台框架对比:vue-element-plus-admin、vue-pure-admin等
前端·ui·框架·vue3
终端鹿6 天前
Vue3 与第三方组件库联动:Element Plus 按需引入与二次封装
vue3·element plus·二次封装
Grocery store owner11 天前
vue3使用wangeditor上传附件以及添加表格,可以直接复制粘贴excel内容
vue3·wangeditor
floret. 小花12 天前
Vue3 知识点总结 · 2026-03-27
前端·面试·electron·学习笔记·vue3
梵得儿SHI13 天前
Vue 3 生态工具实战:UI 组件库与表单验证完全指南
前端·ui·vue3·elementplus·表单验证·antdesignvue·veevalidate
A_nanda13 天前
Vue项目升级
前端·vue3·vue2
创梦流浪人15 天前
soli-admin一款开箱即用的RBAC后台项目
java·spring boot·vue3·springsecurity