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>
相关推荐
花归去17 分钟前
echarts 柱状图曲线图
开发语言·前端·javascript
喝拿铁写前端17 分钟前
当 AI 会写代码之后,我们应该怎么“管”它?
前端·人工智能
老前端的功夫21 分钟前
TypeScript 类型魔术:模板字面量类型的深层解密与工程实践
前端·javascript·ubuntu·架构·typescript·前端框架
北辰alk29 分钟前
Vue Router 404页面配置:从基础到高级的完整指南
vue.js
北辰alk34 分钟前
Vue 中的 MVVM、MVC 和 MVP:现代前端架构模式深度解析
vue.js
北辰alk37 分钟前
为什么 Vue 中的 data 必须是一个函数?深度解析与实战指南
vue.js
北辰alk38 分钟前
Vue 的 <template> 标签:不仅仅是包裹容器
vue.js
Nan_Shu_61444 分钟前
学习: Threejs (2)
前端·javascript·学习
北辰alk1 小时前
为什么不建议在 Vue 中同时使用 v-if 和 v-for?深度解析与最佳实践
vue.js
北辰alk1 小时前
Vue 模板中保留 HTML 注释的完整指南
vue.js