Svelte-组件一如何使用组件二中的功能?

问题描述 投票:0回答:1

CompOne如何在CompTwo中运行功能“测试”?

CompOne.svelte

<script>
   import {test} from './CompTwo.svelte'
</script>
<!-- Some style and HTML tags for this component -->

CompTwo.svelte

<script>
   export const test = () => { console.log('testing function') }
</script>
<!-- Some style and HTML tags for this component -->
components svelte
1个回答
1
投票

如果您有此组件的实例并绑定到它,则可以运行子函数。

App.svelte

<script>
  import Component from './Component.svelte';   
  let comp;
</script>

<Component bind:this={comp} />
<button on:click={() => comp.test()}>Do Stuff</button>

Component.svelte

<script>
    export const test = () => console.log('testing');
</script>

Working example

© www.soinside.com 2019 - 2024. All rights reserved.