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)
相关推荐
软件架构师-叶秋16 小时前
Vue3+tyepescript+ElementPlus+Axios前端技术栈
前端·vue3·elementplus
一只小阿乐18 小时前
vue3封装alert 提示组件 仿element-plus
前端·javascript·vue.js·vue3
Sheldon一蓑烟雨任平生1 天前
Vue3 KeepAlive(缓存组件实例)
vue.js·vue3·组件缓存·keepalive·缓存组件实例·onactivated·ondeactivated
Sheldon一蓑烟雨任平生3 天前
Vue3 组件库 Element Plus
vue.js·vue3·element plus·element ui·vue3 常用组件库
全栈前端老曹3 天前
【前端组件封装教程】第3节:Vue 3 Composition API 封装基础
前端·javascript·vue.js·vue3·组合式api·组件封装
Sheldon一蓑烟雨任平生5 天前
Vue3 任务管理器(Pinia 练习)
vue.js·vue3·pinia·任务管理器·pinia 练习
云外天ノ☼5 天前
待办事项全栈实现:Vue3 + Node.js (Koa) + MySQL深度整合,构建生产级任务管理系统的技术实践
前端·数据库·vue.js·mysql·vue3·koa·jwt认证
行走的陀螺仪6 天前
uni-app + Vue3 实现折叠文本(超出省略 + 展开收起)
前端·javascript·css·uni-app·vue3
Sheldon一蓑烟雨任平生8 天前
Vue 用户管理系统(路由相关练习)
vue.js·vue3·axios·json-server·vue-router·vue 路由·vue-link
Sheldon一蓑烟雨任平生8 天前
Vue3 插件(可选独立模块复用)
vue.js·vue3·插件·vue3 插件·可选独立模块·插件使用方式·插件中的依赖注入