面试题答案
一键面试父组件向子组件传递数据
- 在父组件中:
- 在引入子组件标签时,通过属性绑定的方式传递数据。例如,假设子组件为
<ChildComponent>
,父组件有一个数据parentData
:
<script> import ChildComponent from './ChildComponent.svelte'; let parentData = 'Hello from parent'; </script> <ChildComponent data={parentData} />
- 在引入子组件标签时,通过属性绑定的方式传递数据。例如,假设子组件为
- 在子组件中:
- 使用
export let
来接收父组件传递的数据。在ChildComponent.svelte
中:
<script> export let data; </script> <p>{data}</p>
- 这样就可以在子组件中使用从父组件传递过来的数据,并进行相应的处理,比如显示、计算等。
- 使用
子组件向父组件反馈数据
- 在子组件中:
- 定义一个事件,通过
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>
- 定义一个事件,通过
- 在父组件中:
- 在引入子组件标签时,监听子组件触发的事件。
<script> import ChildComponent from './ChildComponent.svelte'; const handleChildData = (event) => { console.log('Received data from child:', event.detail); }; </script> <ChildComponent on:child - data - event={handleChildData} />
- 父组件通过监听子组件触发的事件,并在事件处理函数中处理子组件反馈的数据。