【发布时间】:2021-12-21 10:32:18
【问题描述】:
用例:我有几个 Svelte 组件被编译为标准 Svelte 应用程序(即,不是 Web 组件),然后用于增强主 Svelte 应用程序的功能。
我正在使用典型的app = new SvelteApp({target, props}) 方法通过包装器/代理组件(如suggested in this answer)实例化它们,这样我就可以执行以下操作:
MainApp.svelte
<script>
import ComponentWrapper from 'ComponentWrapper.svelte'
const App1 = window.app1; // this is standalone/compiled Svelte app
</script>
<ComponentWrapper this={App1} prop1="one" prop2="two" />
ComponentWrapper.svelte
<script>
import { onDestroy } from 'svelte';
let component;
export { component as this };
let target;
let cmp;
const create = () => {
cmp = new component( {
target,
props: $$restProps,
} );
};
const cleanup = () => {
if ( !cmp ) return;
cmp.$destroy();
cmp = null;
};
$: if ( component && target ) {
cleanup();
create();
}
$: if ( cmp ) {
cmp.$set( $$restProps );
}
onDestroy( cleanup );
</script>
<div bind:this={target} />
这很好用,只是我无法使用 ComponentWrapper 上的 on:event={} 指令或其中的 div 元素监听 App1 和 App2 调度的事件。
我的问题是:
-
有没有更好的方法来包含独立的 Svelte 应用程序?
-
如何让活动发挥作用?当然,我可以将方法作为道具传递并在独立应用程序中使用它,但如果可能的话,我宁愿调度/监听事件。
【问题讨论】:
标签: svelte svelte-3 svelte-component