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 -->
答案 0 :(得分: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>
答案 1 :(得分:1)
我遇到了同样的问题,但是我可能会找到解决方法。
在子组件中,您可以声明
<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
干杯!