人间熙攘,好久不见

vuePress-theme-reco Magic    2017 - 2023
人间熙攘,好久不见 人间熙攘,好久不见

Choose mode

  • dark
  • auto
  • light
Home
Category
  • tools
  • Zsh
  • iTerm2
  • Front-end
  • 版本控制-Git
  • Rust
  • skia-safe
  • 第三方对接
  • MQTT
  • Powershell
  • python
  • MD5
  • SHA1
  • wsl2
Tags
TimeLine
GitHub
  • Github (opens new window)
  • Before (opens new window)
author-avatar

Magic

23

文章

15

标签

Home
Category
  • tools
  • Zsh
  • iTerm2
  • Front-end
  • 版本控制-Git
  • Rust
  • skia-safe
  • 第三方对接
  • MQTT
  • Powershell
  • python
  • MD5
  • SHA1
  • wsl2
Tags
TimeLine
GitHub
  • Github (opens new window)
  • Before (opens new window)
  • FrontEnd

    • 使用 Vue + TypeScript 开发 Chrome Extensions 🐱‍👤
    • Debounce Throttling ~
    • 从 Echarts 看 Zrender 的使用
    • Performance Yes 🎉
    • Rollup + Typescript => NPM Package
    • Svelte 事件问题

Svelte 事件问题

vuePress-theme-reco Magic    2017 - 2023

Svelte 事件问题

Magic 2022-10-16 Front-endSvelte

# Svelte 事件传递问题

  • 最近想用 Svelte 框架做一个通用组件在项目中使用,但是发现通过 createEventDispatcher 创建的事件不能触发到外部监听事件,具体代码如下:
<svelte:options tag="custom-button" />

<script lang="ts">
  import { createEventDispatcher } from "svelte";

  export let text = "确认";
  const svelteDispatch = createEventDispatcher();

  function handleClick(e) {
    console.log("点击了?");
    return svelteDispatch("clickNotify", {
      text: "点击了123",
    });
  }
</script>

<button on:click={handleClick}>{text}</button>

通过 rollup -c 打包后 在 vue 项目中使用发现 监听不到事件:





 
 
 




 






<script setup>
import { ref } from "vue";
import "./lib/dist/index";
const text = ref("测试1");
function clickNotify(params) {
  console.log("params", params);
}
</script>

<template>
  <header>
    <custom-button :text="text" @clickNotify="clickNotify" />
  </header>
  <main>
    ...
  </main>
</template>

# 解决

  • 需要通过使用 组件的 $on 方法才能坚挺到,而且在 svelte 组件内必须使用组件的 dispatchEvent 才行,代码如下:




 



 


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 




<svelte:options tag="custom-button" />

<script lang="ts">
  import { createEventDispatcher } from "svelte";
  import { get_current_component } from "svelte/internal";

  export let text = "确认";

  const thisComponent = get_current_component();
  const svelteDispatch = createEventDispatcher();

  function handleClick(e) {
    console.log("点击了?");

    thisComponent.dispatchEvent(
      new CustomEvent("clickNotify", {
        detail: {
          text: "点击了",
        },
      })
    );
    // 这里是必须使用 return 返回
    return svelteDispatch("clickNotify", {
      text: "点击了123",
    });
  }
</script>

<button on:click={handleClick}>{text}</button>
  • 具体是什么原因导致的也不确定,等待后续查看资料吧 😊
欢迎来到 人间熙攘,好久不见
看板娘