问题描述
假设一个外部组件包含一个内部组件,我们希望将来自内部组件的事件传播到外部组件.在不使用商店的情况下,有两种方法可以做到这一点:
Let's say an Outer component contains an Inner component, and we want an event from the Inner component to be propagated to the Outer component. Without using the store, there are 2 ways to do this:
Inner.svelte:使用 Svelte 的调度器来调度原始事件的重新打包版本:
Inner.svelte: Use Svelte's dispatcher to dispatch a repackaged version of the original event:
<input type="text" on:input={callDispatcher} />
const dispatcher = createEventDispatcher();
function callDispatcher(e) {
dispatcher("mymsg", {
foo: e.target.value
});
}
Outer.svelte:监听 Inner 的调度事件:
Outer.svelte: Listen for Inner's dispatched event:
<Inner on:mymsg={handler} />
function handler(e) {
alert(e.detail.foo);
}
方法二:将Outer的handler直接传给Inner
Inner.svelte:接受外部传入的处理程序:
Method 2: Pass Outer's handler directly to Inner
Inner.svelte: Accepts handler passed in by Outer:
export let externalHandler;
<input type="text" on:input={externalHandler} />
Outer.svelte:当 Inner 感兴趣的事件发生时,它会调用 Outer 的处理程序:
Outer.svelte: When Inner event of interest occurs, it will call Outer's handler:
<Inner externalHandler={handler} />
function handler(e) {
alert(e.target.value);
}
问题
哪个是更好的做法?方法一的dispatcher似乎是一个不必要的中间层,不仅增加了更多的代码,而且丢失了原来的事件信息.但奇怪的是,Svelte 教程提到了方法 1 而不是方法 2.
Question
Which one is a better practice? Method 1's dispatcher seems to be an unnecessary middle-layer that not only adds more code but also loses the original event information. But strangely, the Svelte tutorial mentions Method 1 instead of Method 2.
推荐答案
没有真正的区别,您确实可以同时使用两者.但是,方法 2 不适用于 native 元素,让您混合使用这两种方法,您会得到如下代码:
There is no real difference and you can indeed use both.However, method 2 will not work for native elements, leaving you with a mix of both approaches and you get cod like this:
<Child clickHandler="{childClick}" />
<button on:click="{buttonClick}">click</button>
您必须始终记住何时使用哪个,而如果您使用调度程序方法,则总是相同
You would always have to remember when to use which one, while if you use the dispatcher method this will always be the same
<Child on:click="{childClick}" />
<button on:click="{buttonClick}">click</button>
额外的调度程序代码是一种权衡.
The extra dispatcher code is a trade-off in this.
这篇关于Svelte:使用调度程序转发事件与传入处理函数,哪个是最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!