首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >svelte -从一系列嵌套组件中的特定组件调用函数

svelte -从一系列嵌套组件中的特定组件调用函数
EN

Stack Overflow用户
提问于 2020-12-08 18:30:16
回答 1查看 195关注 0票数 0

我有一个nested组件,我将在应用程序中实例化多个副本:

代码语言:javascript
复制
//App.svelte
<Nested /> // Nested-1 
<Nested /> // Nested-2
<Nested /> // Nested-3

Nested中,我导出了一个函数:

代码语言:javascript
复制
//Nested.svelte
export function doExample(){...}

Nested-2中调用doExample()的最佳方式是什么?我能想到的一种方法是在Nested中使用id

代码语言:javascript
复制
//App.svelte
<Nested id="nested_1" /> // Nested-1 
<Nested id="nested_2" /> // Nested-2
<Nested id="nested_3" /> // Nested-3

然后使用getElementById()识别特定组件,然后调用函数。但有没有更好的方法来实现这一点呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-08 21:21:41

为此,您可以在实例上使用bind,然后在该实例上调用函数

代码语言:javascript
复制
<script>
  import Nested from './Nested.svelte'
  let child
  
  const action = () => child.doExample()
</script>

<Nested bind:this={child} />

请注意,这也适用于数组:

代码语言:javascript
复制
<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}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65197204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档