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)
相关推荐
Sapphire~1 天前
Vue3-14 watch监视对象及对象属性,watchEffect
vue3
技术宅星云1 天前
7. vue3-element-admin 二次开发图文教程
vue3·element-admin·后端开箱即用前端框架
Sheldon一蓑烟雨任平生2 天前
Sass 星空(Sass + keyframes 实现星空动画)
前端·css·vue3·sass·keyframes
Irene19913 天前
Vue 3 中移除了 $on、$off 和 $once 方法(附:Composables 组合式函数 使用详解)
vue3
Sapphire~4 天前
Vue3-15 html标签和组件上的ref属性 + 接口泛型
vue3
Irene19914 天前
Vue 3 中使用 Mitt 事件总线
vue3·mitt
咸甜适中4 天前
双色球、大乐透兑奖分析小程序(rust_Tauri + Vue3 + sqlite)
爬虫·rust·sqlite·vue3·tauri2
Sapphire~6 天前
Vue3-012 vue2与vue3中的computed
vue3
Sapphire~9 天前
Vue3-11 toRefs 和 toRef
vue3
华玥作者10 天前
uni-app + Vite 项目中使用 @uni-helper/vite-plugin-uni-pages 实现自动路由配置(超详细)
前端·uni-app·vue·vue3·vite