简体   繁体   English

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

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

Now I'm confused how to fire function from component to control something in another component.现在我很困惑如何从组件中触发 function 来控制另一个组件中的某些东西。 Can anyone help me on this?谁可以帮我这个事?

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);
}

I have a button in checklist component that want to activate function that in stage component.我在清单组件中有一个按钮想要激活阶段组件中的 function。

Stage component is a map that have xy position and function that move things inside this component. Stage 组件是一个 map,它有 xy position 和 function,可以在这个组件内移动东西。

How can I call function in stage component from the outside (checklist components)?如何从外部(清单组件)在阶段组件中调用 function?

You have a couple of options:你有几个选择:

first and the most flexible one is to create a writable store to use it anywhere第一个也是最灵活的一个是创建一个可写store以在任何地方使用它

second it to use context其次它使用context

third is to declare it in App.svelte and bind it to both children第三种是在App.svelte中声明并bind到两个孩子

You could do the following:您可以执行以下操作:

  1. Dispatch a custom checklist-click event from Checklist.从 Checklist 调度自定义checklist-click事件。
  2. In App, listen to this click event and call fly on Stage.在 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>

For more on dispatching component events, see the Svelte tutorial .有关调度组件事件的更多信息,请参阅Svelte 教程

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

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