簡體   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