【问题标题】:svelte - call function from specific component in a series of nested componentssvelte - 从一系列嵌套组件中的特定组件调用函数
【发布时间】:2020-12-08 21:21:40
【问题描述】:

我有一个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() 识别特定组件然后调用该函数。但是有没有更好的方法来实现这一点?

【问题讨论】:

    标签: javascript svelte-3 svelte-component


    【解决方案1】:

    您可以通过在实例上使用 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}
    

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      相关资源
      最近更新 更多