怎样在 Svelte 中设置自定义事件

正文

不同于 React 中以 props 传递,Svelte 中的自定义事件更加类似 Vue,不过需要使用 createEventDispatcher() 构建一个事件派发器,而这一步在 Vue 中是使用 this.$emit() 实现的。

下面是子组件Nested.svelte,自定义事件将会在这里触发:

<script>
  import { createEventDispatcher } from "svelte";
  const emit = createEventDispatcher();
  const clickHandler = () => {
    emit("click", "hello");
  };
</script>

<button on:click={clickHandler}>click</button>

这是父组件App.svelte,只需要按照惯常的事件绑定方法写好即可:

<script>
  import Button from "./Nested.svelte";
  const clickHandler = (e) => alert(e.detail);
</script>

<div>
  This is a btn. <br />
  <Button on:click={clickHandler} />
</div>

<style>
  div {
    padding: 30px 15px;
    background-color: #f1f8fd;
  }
</style>

参考

https://www.sveltejs.cn/tutorial/component-events

posted on 2021-06-09 14:40  右究  阅读(120)  评论(0编辑  收藏  举报

导航