zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    leetcode931
    leetcode1289
    leetcode1286
    poj Meteor Shower
    noip杂题题解
    noip2007部分题
    NOIP Mayan游戏
    某模拟题题解
    codevs 1423 骑士
    noip 邮票面值设计
  • 原文地址:https://www.cnblogs.com/aisowe/p/15245528.html
Copyright © 2011-2022 走看看