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>
相关推荐
满怀101528 分钟前
【Vue 3全栈实战】从响应式原理到企业级架构设计
前端·javascript·vue.js·vue
luckywuxn38 分钟前
使用gitbook 工具编写接口文档或博客
前端
梅子酱~1 小时前
Vue 学习随笔系列二十三 -- el-date-picker 组件
前端·vue.js·学习
伟笑1 小时前
elementUI 循环出来的表单,怎么做表单校验?
前端·javascript·elementui
辣辣y1 小时前
React中useMemo和useCallback的作用:
前端·react
Alice-YUE1 小时前
【HTML5学习笔记1】html标签(上)
前端·笔记·学习·html·html5
Alice-YUE1 小时前
【HTML5学习笔记2】html标签(下)
前端·笔记·html·html5
确实菜,真的爱1 小时前
electron进程通信
前端·javascript·electron
源码云商2 小时前
【带文档】网上点餐系统 springboot + vue 全栈项目实战(源码+数据库+万字说明文档)
数据库·vue.js·spring boot
!win !3 小时前
uni-app小程序登录后…
前端·uni-app