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>
相关推荐
yingyima2 分钟前
Nginx 配置速查手册:核心语法与实战案例
前端
梨子同志3 分钟前
开发工具
前端·后端
像我这样帅的人丶你还8 分钟前
Java 后端详解(六):Maven 与本地开发指南
前端·后端
触底反弹8 分钟前
🎲 纯 CSS 搞定 3D 旋转立方体?还附赠一个「天坑」解决方案!
前端·css·html
盗德12 分钟前
LangChain.js 中文开发手册(记录)
前端
༄沐࿆风࿆࿆1 小时前
JavaScript函数完全指南:从基础语法到闭包原理与应用实战
开发语言·javascript
Geek-Chow1 小时前
微服务认证与授权:01 — 概念
java·前端·数据库
finyouIT1 小时前
锚点实现了点击导航平滑滚动到页面指定位置的三种方法
javascript·css
狂炫冰美式1 小时前
凌晨睡不着,我给台风巴威写了个追踪网站
前端·后端·github
雪隐2 小时前
用Flutter做背单词APP-01服务器?不存在的,我家里就有
前端·人工智能·后端