1 回答
TA贡献1818条经验 获得超3个赞
你可以做这样的:
<script>
import ChartA from './ChartA.svelte'
import ChartB from './ChartB.svelte'
import ChartC from './ChartC.svelte'
let charts = [
ChartA,
ChartB,
ChartC
];
let events = [];
</script>
<style>
.icon{
width:60px;
height:30px;
background-color:grey;
}
</style>
{#each charts as chart, i}
<div class="wrapper">
<div class="icon" on:click={e=>events[i] = e}>Click</div>
<div class="content">
<svelte:component this={charts[i]} event={events[i]}/>
</div>
</div>
{/each}
不过,将事件作为数据传递会有点不寻常。更习惯的做法是在父组件中设置一些状态以响应事件,并将该状态向下传递。
或者,如果子组件确实需要自己响应事件,您可以采用这种方法......
<script>
import ChartA from './ChartA.svelte'
import ChartB from './ChartB.svelte'
import ChartC from './ChartC.svelte'
let charts = [
ChartA,
ChartB,
ChartC
];
let instances = [];
</script>
<style>
.icon{
width:60px;
height:30px;
background-color:grey;
}
</style>
{#each charts as chart, i}
<div class="wrapper">
<div class="icon" on:click={e => instances[i].handle(e)}>Click</div>
<div class="content">
<svelte:component
this={charts[i]}
bind:this={instances[i]}
/>
</div>
</div>
{/each}
...其中每个子组件导出一个handle方法:
<script>
let event;
export function handle(e){
event = e;
};
</script>
添加回答
举报