是否可以创建一个组件并以编程方式将事件侦听器附加到它?
我知道这对于使用<svelte:component/>
传播的道具很容易实现{ ...props }
。我想知道是否可以实现类似的附加事件侦听器。
例如,在以下示例中,我想以编程方式附加on:message
到A
和on:count
到B
:
<!-- App.svelte -->
<script>
import A from './A.svelte';
import B from './B.svelte';
let message = 'Hi there ';
let count = 0;
const components = [{
component: A,
props: { message },
listeners: { message: (m) => { console.log(`They say "${m}"`); } }
}, {
component: B,
props: { count },
listeners: { click: () => { count++; } }
}];
</script>
{#each components as component}
<div><svelte:component this={component.component} { ...component.props }/></div>
{/each}
<div>
<p>They say "{message}"!</p>
<p>They clicked {count} times!</p>
</div>
<!-- A.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let message = '';
function changeHandler(e) { dispatch('message', message); }
</script>
<input on:change={changeHandler} on:value={message} value={message} />
<!-- B.svelte -->
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let count = 0;
function clickHandler() { dispatch('count', count); }
</script>
<button on:click={clickHandler}>Click me</button>
这是一个现场演示:https ://svelte.dev/repl/af1bd30ab75b43f19b72a306340b7282?version=3.18.2
即,我希望有一种方法可以将components
数组扩展到
<A message={message} on:message={e => { message = e.detail; }}/>
<B count={count} on:count={e => { count = e.detail; }}/>