Vue3 手写函数式悬浮窗

本文介绍了如何在Vue中创建一个可定制的弹窗组件Snackbars.vue,包括模板、TS编写、颜色和动画设置,以及在其他组件中通过`showTips`对象调用不同类型的弹窗消息。
摘要由CSDN通过智能技术生成

首先需要写一个弹窗组件 Snackbars.vue

<template>
  <transition name="fade" @after-leave="destroy">
    <div class="text-center"
        v-show="isVisable">
        {{ message }}
    </div>
  </transition>
</template>

<script setup lang="ts">
const props = defineProps({
    color:{
        type: String,
        default: "red"
    },
    message:{
        type: String,
        default: "affff"
    },
    duration:{
        type: Number,
        default: 500
    },
    destroy: Function
})

const isVisable = ref(false);

onMounted(()=> {
    isVisable.value =true
    setTimeout(()=>{
        isVisable.value = false
    }, props.duration)
})
</script>

<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
 transition: all 0.5s;
}
​
.fade-enter-from,
.fade-leave-to {
 opacity: 0;
 transform: translate3d(-50%, -100%);
}
.text-center{
    display: flex;
    position: fixed;
    top: 60%;
    right: 0px;
    border: 1px solid #000;
    background: v-bind('props.color'); // 绑定传参颜色
    z-index: 999;
}
</style>

第二步 渲染组件,写一个ts文件:showTips.ts

import { h, render } from 'vue';
import Snackbar from "./Snackbars.vue";
export const showTips = {
    success:(message:String, duration=5000, color="#4CAF50")=>{
        showTips.create(message, duration, color)
    },
    error:(message:String, duration=5000, color="D32F2F")=>{
        showTips.create(message, duration, color)
    },
    warn:(message:String, duration=5000, color="F57C00")=>{
        showTips.create(message, duration, color)
    },
    create:(message:String, duration:Number, color:String)=>{
        const handleDestroy = () => {
            render(null, document.body)
        }
        // 使用 h 函数创建 vnode
        const vnode = h(Snackbar, {
            message,
            color,
            duration,
            destroy: handleDestroy
        })
        // 使用 render 函数将 vnode 渲染为真实DOM并挂载到 body 上
        render(vnode, document.body)
    }

}

第三步在其他组件引用的时候导入

import {showTips} from '@/components/Snackbars/showTips'

showTips.success("Change successful")

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值