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>
相关推荐
文心快码BaiduComate几秒前
双十一将至,用Rules玩转电商场景提效
前端·人工智能·后端
用户18729422508392 分钟前
告别函数的“两面派”人生:深度剖析箭头函数如何一劳永逸地解决 ‘this’ 的二义性
javascript
拉不动的猪3 分钟前
关于scoped样式隔离原理和失效情况&&常见样式隔离方案
前端·javascript·面试
摇滚侠4 分钟前
Vue 项目实战《尚医通》,医院详情菜单与子路由,笔记17
前端·vue.js·笔记
有来技术6 分钟前
vite-plugin-vue-mcp:在 Vue 3 + Vite 中启用 MCP,让 AI 理解并调试你的应用
前端·vue.js·人工智能
fruge10 分钟前
前端本地存储进阶:IndexedDB 封装与离线应用开发
前端
忍者扔飞镖17 分钟前
欧服加载太慢了,咋整
前端·性能优化
鹏北海27 分钟前
Vue 3 超强二维码识别:多区域/多尺度扫描 + 高级图像处理
前端·javascript·vue.js
Jack莱杰27 分钟前
Math.js封装工具库(解决前端因为浮点数导致计算错误)
javascript
Android疑难杂症29 分钟前
一文讲清鸿蒙网络开发
前端·javascript·harmonyos