父组件通过Props传递数据给子组件
- 在父组件中:在使用子组件标签时,通过属性名=“值” 的形式传递数据。例如:
<script>
let dataToChild = "Hello from parent";
</script>
<ChildComponent data={dataToChild} />
- 在子组件中:通过
export let
来接收父组件传递的数据。例如:
<script>
export let data;
</script>
<p>{data}</p>
子组件通过事件派发将信息反馈给父组件
- 在子组件中:使用
createEventDispatcher
创建事件派发器,然后在需要的地方调用它来触发事件并传递数据。例如:
<script>
import { createEventDispatcher } from'svelte';
const dispatch = createEventDispatcher();
function sendDataToParent() {
dispatch('customEvent', { message: 'Hello from child' });
}
</script>
<button on:click={sendDataToParent}>Send data to parent</button>
- 在父组件中:在使用子组件标签时,通过
on:自定义事件名
的形式监听子组件触发的事件,并在事件处理函数中接收子组件传递的数据。例如:
<script>
function handleChildEvent(event) {
console.log(event.detail.message);
}
</script>
<ChildComponent on:customEvent={handleChildEvent} />