MST

星途 面试题库

面试题:Svelte组件自定义事件中的双向绑定处理

在Svelte应用中,有一个子组件包含一个输入框。要求在子组件输入框内容变化时,触发自定义事件将新内容传递给父组件,同时父组件能通过双向绑定机制实时更新子组件输入框的值。请阐述实现思路并给出关键代码示例。
25.8万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 子组件
    • 使用 bind:value 绑定输入框的值,以便获取输入框内容变化。
    • 当输入框内容变化时,通过 createEventDispatcher 创建的事件分发器触发自定义事件,并将输入框的值作为参数传递给父组件。
  2. 父组件
    • 在使用子组件标签时,通过 bind:childValue 双向绑定一个变量,这里 childValue 是自定义名称,表示子组件输入框的值。
    • 在子组件标签上监听子组件触发的自定义事件,事件处理函数中更新双向绑定的变量,从而实现实时更新子组件输入框的值。

关键代码示例

子组件(例如 Child.svelte

<script>
    import { createEventDispatcher } from'svelte';
    const dispatch = createEventDispatcher();
    let value;
    const handleChange = () => {
        dispatch('inputChange', value);
    };
</script>

<input type="text" bind:value on:input={handleChange}>

父组件(例如 Parent.svelte

<script>
    let childValue = '';
    const handleChildChange = (event) => {
        childValue = event.detail;
    };
</script>

<Child bind:childValue on:inputChange={handleChildChange} />