通过 JS调用的方式来创建组件,使用场景:弹窗、消息通知等 以 Notice 组件为例,首先创建 Nitoce 组件 <!-- Notice.svelte --> <script lang="ts"> import type { MainNoticeEvent, MainNoticeLeval } from '$lib/services/events/Notice'; import * as AlertDialog from '$lib/components/ui/alert-dialog'; const { title, message, level, content, onClose }: MainNoticeEvent<MainNoticeLeval> & { onClose: () => void; } = $props(); </script> <AlertDialog.Root open={true}> <AlertDialog.Content> <AlertDialog.Header> <AlertDialog.Title>{title || '通知'}{level}</AlertDialog.Title> <AlertDialog.Description> {message} </AlertDialog.Description> </AlertDialog.Header> <div>{content}</div> <AlertDialog.Footer> <AlertDialog.Action on:click={onClose}>关闭</AlertDialog.Action> </AlertDialog.Footer> </AlertDialog.Content> </AlertDialog.Root> 创建 Notice 类 import type { MainNoticeEvent, MainNoticeLeval } from '$lib/services/events/Notice'; import { mount, unmount } from 'svelte'; import Notice from './Notice.svelte'; class NoticeManage { private noticeIds: Map<number, Record<string, any>>; constructor() { this.noticeIds = new Map(); } close(id: number) { const notice = this.noticeIds.get(id); if (notice) { unmount(notice); this.noticeIds.delete(id); } } open(props: MainNoticeEvent<MainNoticeLeval>) { const notice = mount(Notice, { target: document.body, props: { ...props, onClose: () => this.close(props.id) } }); this.noticeIds.set(props.id, notice); } } const noticeManage = new NoticeManage(); export default noticeManage; 使用 noticeManage.open({ id: 123, title: '通知', message: '通知内容', level: 'info', content: '通知内容content' });