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 天前
vite+vue3开发uni-app时低版本浏览器不支持es6语法的问题排坑笔记
前端·uni-app·es6·vue3·vite·babel·兼容
前端熊猫5 天前
Vue 3 生命周期和生命周期函数
前端·javascript·vue.js·vue3·生命周期函数
西门吹雪~7 天前
【前端面试】在Vue3中,beforeMount和mounted钩子函数有什么区别?
前端·javascript·vue.js·前端框架·vue3
西门吹雪~8 天前
Vue3 从入门到精通:全面掌握前端框架的进阶之路
vue.js·前端框架·vue3
西门吹雪~8 天前
【前端框架】Vue3 中 `setup` 函数的作用和使用方式
前端·javascript·vue.js·前端框架·vue3
西门吹雪~9 天前
【前端框架】Vue3 面试题深度解析
前端·前端框架·vue·vue3·前端面试
西门吹雪~9 天前
【前端框架】vue2和vue3的区别详细介绍
前端·javascript·vue.js·前端框架·vue3·vue2
西门吹雪~9 天前
【前端框架】深入Vue 3组件开发:构建高效灵活的前端应用
前端·vue.js·前端框架·vue3
患得患失94911 天前
【前端】【面试】ref与reactive的区别
前端·面试·vue3
sakuraxiaoyu14 天前
MHTML文件如何在前端页面展示
前端·html·vue3·js·mhtml