MST

星途 面试题库

面试题:Svelte组件化开发中如何传递和处理组件间数据

在Svelte组件化开发入门场景下,假设已有一个父组件和一个子组件,阐述如何将父组件中的数据传递给子组件,并在子组件中进行相应处理,同时说明如何实现子组件向父组件反馈数据。
20.4万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

父组件向子组件传递数据

  1. 在父组件中
    • 在引入子组件标签时,通过属性绑定的方式传递数据。例如,假设子组件为<ChildComponent>,父组件有一个数据parentData
    <script>
      import ChildComponent from './ChildComponent.svelte';
      let parentData = 'Hello from parent';
    </script>
    
    <ChildComponent data={parentData} />
    
  2. 在子组件中
    • 使用export let来接收父组件传递的数据。在ChildComponent.svelte中:
    <script>
      export let data;
    </script>
    
    <p>{data}</p>
    
    • 这样就可以在子组件中使用从父组件传递过来的数据,并进行相应的处理,比如显示、计算等。

子组件向父组件反馈数据

  1. 在子组件中
    • 定义一个事件,通过createEventDispatcher来创建事件分发器。例如,假设子组件有一个按钮,点击按钮时要向父组件反馈数据:
    <script>
      import { createEventDispatcher } from'svelte';
      const dispatch = createEventDispatcher();
      let childData = 'Data from child';
      const sendDataToParent = () => {
        dispatch('child - data - event', childData);
      };
    </script>
    
    <button on:click={sendDataToParent}>Send data to parent</button>
    
  2. 在父组件中
    • 在引入子组件标签时,监听子组件触发的事件。
    <script>
      import ChildComponent from './ChildComponent.svelte';
      const handleChildData = (event) => {
        console.log('Received data from child:', event.detail);
      };
    </script>
    
    <ChildComponent on:child - data - event={handleChildData} />
    
    • 父组件通过监听子组件触发的事件,并在事件处理函数中处理子组件反馈的数据。