[英]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
到两个孩子
您可以执行以下操作:
checklist-click
事件。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.