Svelte 中的事件修饰符

正文

React 中没有事件修饰符,Vue 用的说 @click.once 语法,Svelte 用的是 on:click|once 语法。

<script>
  const clickHandler = (foo) => alert(foo + "trigger");
</script>

<!-- once -->
<div>
  <button on:click|once={clickHandler}>只触发一次: once</button>
</div>

<!-- preventDefault -->
<div>
  <!-- 此时 href 不生效 -->
  <a href="http://www.baidu.com/" on:click|preventDefault={clickHandler}>
    阻止默认行为: preventDefault
  </a>
</div>

<!-- capture -->
<div
  on:click|capture={() => {
    clickHandler("father ");
  }}
>
  <button on:click|capture={() => clickHandler("child ")}>
    让事件触发时机改为:capture
  </button>
</div>

<!-- self -->
<div
  on:click|self={() => {
    clickHandler("father ");
  }}
>
  <button on:click={() => clickHandler("child ")}>
    仅当 event.target 是其本身时才触发:self
  </button>
</div>

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

 

参考

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

导航