vue3使用tsx自定义弹窗组件

1.在ts代码中使用css

我这里使用了@styils/vue,npm install @styils/vue --save-dev,在tsx文件中引入即可:import { styled } from "@styils/vue";

2.在tsx中初始化组件,创建在src的utils目录中创建messagebox.tsx

TypeScript 复制代码
import { createApp} from "vue";
// 这里使用了element-plus的组件,请自行引入即可
import { ElButton } from "element-plus";
import { styled } from "@styils/vue";


const DivModal = styled('div', {
    position: 'fixed',
    width: '100%',
    height: '100%',
    left: 0,
    top: 0,
    background: '#00000050',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center'
});

const DivBox = styled('div', {
    display: 'flex',
    minWidth: '25%',
    background: '#fff',
    padding: '10px 0',
    color: '#333',
    borderRadius: '10px',
    boxShadow: '0 0 3px #00000080',
    flexDirection: 'column',
    alignItems: 'center'
});

const DivText = styled('div', {
    marginBottom: '1em'
});


const Messagebox = {
    props: {
        msg: {
            type: String,
            required: true
        },
    },
    render(ctx: any) {
        const { $props, $emit } = ctx;
        return (
            <DivModal class="modal">
                <DivBox class="box">
                    <DivText class="text">{$props.msg}</DivText>
                    <div onClick={$emit('onClick(e)')}>
						<ElButton type="primary">确 定</ElButton>
					</div>
                </DivBox>
            </DivModal>
        );
    },
};


export function showMsg(msg: String, isModal: Boolean | null, onClickHandler: Function) {
    const div = document.createElement("div");
    document.body.appendChild(div);
    const app = createApp(Messagebox,
        {
            msg,
            onClick(e: any) {
				if (isModal) {
					onClickHandler(() => {
						app.unmount();
						div.remove();
					});
				} else {
					const isButton = e.target.localName === "button" || e.target.innerText === "确定";
					if (isButton) {
						onClickHandler(() => {
							app.unmount();
							div.remove();
						});
					}
				}
            }
        }
    );
    app.mount(div);
};

3.在vue中使用该组件

html 复制代码
<template>
    <el-button type="primary" @click="showTsxMsg">显示tsx封装的弹窗</el-button>
</template>

<script lang="ts" setup>
import { showMsg } from "@/utils/messagebox";

const showTsxMsg = () => {
    showMsg("tsx封装的组件", true, (close: Function) => {
        close();
    });
};
</script>
相关推荐
红尘散仙9 分钟前
四、WebGPU 基础入门——Uniform 缓冲区与内存对齐
前端·rust·gpu
进取星辰20 分钟前
13、性能优化:魔法的流畅之道——React 19 memo/lazy
前端·react.js·前端框架
zwjapple26 分钟前
React中createPortal 的详细用法
前端·javascript·react.js
小矮马27 分钟前
React-组件通信
前端·javascript·react.js
codingandsleeping36 分钟前
pnpm + monorepo:高效的项目管理方式
前端
程序员三千_1 小时前
最近爆火的MCP到底是什么?
前端
古时的风筝1 小时前
暴论:2025年,程序员必学技能就是MCP
前端·后端·mcp
古时的风筝1 小时前
这编程圈子变化太快了,谁能告诉我 MCP 是什么
前端·后端·mcp
王月lydia1 小时前
环境变量篇-vue3的H5项目从0到1工程化落地经验篇2
前端
赵要上天1 小时前
利用TTP协议 ETag + 路由守卫 实现前端发版后通知用户更新得一个方案
前端