MST
星途 面试题库

面试题:Svelte中如何在子组件实现事件派发通知父组件

请描述在Svelte中,子组件通过事件派发通知父组件的基本步骤,并给出一个简单的代码示例,示例需包含子组件和父组件的代码。
17.3万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

基本步骤

  1. 在子组件中使用 createEventDispatcher 创建一个事件派发器。
  2. 在子组件的适当逻辑位置,通过事件派发器触发自定义事件,并可以传递数据。
  3. 在父组件中引入子组件,并使用 on:自定义事件名 的语法来监听子组件派发的事件,并定义处理函数。

代码示例

子组件(Child.svelte)

<script>
    import { createEventDispatcher } from'svelte';
    const dispatch = createEventDispatcher();
    function sendDataToParent() {
        const data = { message: 'Hello from child' };
        dispatch('childEvent', data);
    }
</script>

<button on:click={sendDataToParent}>Send data to parent</button>

父组件(Parent.svelte)

<script>
    import Child from './Child.svelte';
    function handleChildEvent(data) {
        console.log('Received data from child:', data.message);
    }
</script>

<Child on:childEvent={handleChildEvent} />