繁体   English   中英

如何从另一个组件调用function到另一个组件

[英]How to call function from another component to another component

现在我很困惑如何从组件中触发 function 来控制另一个组件中的某些东西。 谁可以帮我这个事?

Structure:
App.svelte
L checklist.svelte
  L button <-- this button want to call function in stage component
L stage.svelte
checklist.svelte:
<button on:click="handleMove" />
stage.svelte:
export function fly(x, y) {
   $map.flyto(x, y);
}

我在清单组件中有一个按钮想要激活阶段组件中的 function。

Stage 组件是一个 map,它有 xy position 和 function,可以在这个组件内移动东西。

如何从外部(清单组件)在阶段组件中调用 function?

你有几个选择:

第一个也是最灵活的一个是创建一个可写store以在任何地方使用它

其次它使用context

第三种是在App.svelte中声明并bind到两个孩子

您可以执行以下操作:

  1. 从 Checklist 调度自定义checklist-click事件。
  2. 在 App 中,监听这个点击事件,在 Stage 上调用fly
<!-- App.svelte -->
<script>
    import Checklist from './Checklist.svelte';
    import Stage from './Stage.svelte';
    
    let stage;
    
    function handleClick({ detail }) {
        // these come from the second argument to dispatch in Checklist.svelte
        const { x, y } = detail;
        stage.fly(x, y);
    }
</script>

<h1>App</h1>

<!-- Listen to the event fired with dispatch('checklist-click') -->
<Checklist on:checklist-click={handleClick}></Checklist>

<!-- Store a reference to this component instance so that we can call `fly` on it -->
<Stage bind:this={stage}></Stage>

<!-- Checklist.svelte -->
<script>
    import { createEventDispatcher } from 'svelte';
    const dispatch = createEventDispatcher();
    
    function handleMove() {
        dispatch('checklist-click', {x: 5, y: 10});
    }
</script>

<h2>Checklist</h2>

<button on:click={handleMove}>
    Move
</button>

<!-- Stage.svelte -->
<script>
    export function fly(x, y) {
        console.log(`fly called from stage with x: ${x}, y: ${y}`);
    }
</script>


<h2>Stage</h2>

有关调度组件事件的更多信息,请参阅Svelte 教程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM