- 状态管理方案设计:
- 使用Svelte的上下文(Context API)来在组件树中共享状态。顶层组件将状态和更新状态的函数通过
setContext
传递下去,深层子组件和中间层组件通过getContext
获取。
- 中间层组件可以在状态变化时,利用
$:
语句来触发副作用操作。
- 核心代码示例:
<script>
import { setContext } from'svelte';
import MiddleComponent from './MiddleComponent.svelte';
let sharedValue = 0;
const updateSharedValue = (newValue) => {
sharedValue = newValue;
};
setContext('sharedContext', {
sharedValue,
updateSharedValue
});
</script>
<MiddleComponent />
- 中间层组件(MiddleComponent.svelte):
<script>
import { getContext } from'svelte';
import DeepComponent from './DeepComponent.svelte';
const { sharedValue, updateSharedValue } = getContext('sharedContext');
$: {
// 这里可以触发与sharedValue变化相关的副作用操作
console.log('Shared value in middle component has changed to:', sharedValue);
}
</script>
<DeepComponent />
- 深层子组件(DeepComponent.svelte):
<script>
import { getContext } from'svelte';
const { sharedValue, updateSharedValue } = getContext('sharedContext');
</script>
<button on:click={() => updateSharedValue(sharedValue + 1)}>Increment Shared Value</button>
<p>The shared value is: {sharedValue}</p>