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)
相关推荐
你说啥名字好呢4 天前
【Vue 渲染流程揭秘】
前端·javascript·vue.js·vue3·源码分析
行走的陀螺仪6 天前
vue3-封装权限按钮组件和自定义指令
前端·vue3·js·自定义指令·权限按钮
麦麦大数据7 天前
F046 新闻推荐可视化大数据系统vue3+flask+neo4j
python·flask·vue3·知识图谱·neo4j·推荐算法
Sheldon一蓑烟雨任平生7 天前
Vue3 高级性能优化
性能优化·vue3·tree-shaking·高级性能优化·首屏加载优化·更新优化·大型虚拟列表
前端.攻城狮7 天前
用fetch-event-source处理流式消息:Vue 3中实现openAI/DeepSeek的实时输出
vue3·流式消息
Sheldon一蓑烟雨任平生9 天前
webpack 从零构建 Vue3
webpack·typescript·vue3·webpack配置·从零构建vue3
saadiya~10 天前
基于 Vue3 封装大华 RTSP 回放视频组件(PlayerControl.js 实现)
前端·vue3·大华视频相机前端播放
软件架构师-叶秋11 天前
Vue3+tyepescript+ElementPlus+Axios前端技术栈
前端·vue3·elementplus
一只小阿乐11 天前
vue3封装alert 提示组件 仿element-plus
前端·javascript·vue.js·vue3
Sheldon一蓑烟雨任平生11 天前
Vue3 KeepAlive(缓存组件实例)
vue.js·vue3·组件缓存·keepalive·缓存组件实例·onactivated·ondeactivated