实现思路
- 使用Svelte的响应式声明:Svelte通过
$:
语法来实现响应式,数据变化时自动更新相关DOM。
- 状态提升:将需要共享和修改的状态提升到顶层父组件,通过props将数据传递给子组件。
- 事件机制:子组件通过触发自定义事件将数据变化通知给父组件,父组件更新自身状态,从而实现数据的双向流动。
关键代码片段
- 顶层父组件(App.svelte)
<script>
let sharedData = '初始值';
function handleChildUpdate(newValue) {
sharedData = newValue;
}
</script>
<DeepChild {sharedData} on:childUpdate={handleChildUpdate} />
{#if sharedData}
<p>顶层父组件数据: {sharedData}</p>
{/if}
- 中间层组件(Middle.svelte)
<script>
export let sharedData;
export let onChildUpdate;
</script>
<DeepestChild {sharedData} on:childUpdate={onChildUpdate} />
{#if sharedData}
<p>中间层组件数据: {sharedData}</p>
{/if}
- 深层子组件(DeepestChild.svelte)
<script>
export let sharedData;
const updateData = () => {
const newData = '新的值';
sharedData = newData;
const event = new CustomEvent('childUpdate', { detail: newData });
document.dispatchEvent(event);
};
</script>
<button on:click={updateData}>更新数据</button>
{#if sharedData}
<p>深层子组件数据: {sharedData}</p>
{/if}