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

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

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 -->
fhqjgfhqjg 回答:Svelte-组件一如何使用组件二中的功能?

如果拥有该组件的实例并绑定到该组件,则可以运行子功能。

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

,

我遇到了同样的问题,但是我可能会找到解决方法。

在子组件中,您可以声明

<ChildComponent>
  <script>
    export const myFunc = () => alert('alarm... alarm..');
  </script>
</ChildComponent>

<RootComponent>
  <script>
    import ChildComponent from './ChildComponent.svelte';
    let myFunc;
  </script>

  <ChildComponent bind:myFunc={myFunc} />
  <button on:click={myFunc} >Testing Alarm</button>
</RootComponent>

在这里查看工作示例: Example Svelte - Executing function on child component workaround

干杯!

本文链接:https://www.f2er.com/3164404.html

大家都在问