Svelte 中多层组件事件转发

正文

现在组件的层级是:<Father> 内嵌 <Child><Child> 内嵌 <GrandChild>,如果此时 Father 组件中定义的一个事件监听函数要在 <GrandChild> 组件中触发执行,则必定会经过中间组件:<Child>,下面是 <Child> 组件内的常规设置:

<script>
  import GrandChild from "./GrandChild.svelte";
  import { createEventDispatcher } from "svelte";
  const emit = createEventDispatcher();
  const messageHandler = (e) => {
    emit("message", e.detail);
  };
</script>

<!-- 这是例子需要演示的 -->
<GrandChild on:message={messageHandler} />

 

以上代码中定义的方法只是为了做个中转,这显得较为冗余,所以 Svelte 做了简化,如下:

<script>
  import GrandChild from "./GrandChild.svelte";
</script>

<GrandChild on:message />

 

感觉瞬间清爽了许多,有木有!!

注意

DOM 事件也可以使用这一特性:<button on:click>click</button>

但前提是该组件上绑定了一个同名的 DOM 事件监听函数:<p>child: <Child on:click={clickHandler} /></p>

参考

https://www.sveltejs.cn/tutorial/event-forwarding

posted on 2021-09-09 09:31  aisowe  阅读(60)  评论(0编辑  收藏  举报

导航