首页 > 其他 > 详细

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

时间:2021-09-09 23:38:44      阅读:29      评论:0      收藏:0      [点我收藏+]

正文

不同于 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

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

原文:https://www.cnblogs.com/aisowe/p/15245524.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!