我有一个nested组件,我将在应用程序中实例化多个副本:
//App.svelte
<Nested /> // Nested-1
<Nested /> // Nested-2
<Nested /> // Nested-3在Nested中,我导出了一个函数:
//Nested.svelte
export function doExample(){...}在Nested-2中调用doExample()的最佳方式是什么?我能想到的一种方法是在Nested中使用id
//App.svelte
<Nested id="nested_1" /> // Nested-1
<Nested id="nested_2" /> // Nested-2
<Nested id="nested_3" /> // Nested-3然后使用getElementById()识别特定组件,然后调用函数。但有没有更好的方法来实现这一点呢?
发布于 2020-12-08 21:21:41
为此,您可以在实例上使用bind,然后在该实例上调用函数
<script>
import Nested from './Nested.svelte'
let child
const action = () => child.doExample()
</script>
<Nested bind:this={child} />请注意,这也适用于数组:
<script>
import Nested from './Nested.svelte'
let children = []
const action = i => children[i].doExample()
</script>
{#each array as item, i}
<Nested bind:this={children[i]} />
{/each}https://stackoverflow.com/questions/65197204
复制相似问题