如何根据变量动态订阅不同的Svelte Store?
动态订阅Svelte Store的最优方案
核心思路:用映射表替代if-else判断
通过创建category与对应store的映射对象,可以快速根据路由参数匹配到目标store,同时结合Svelte的响应式特性,自动处理category变化时的订阅切换。
具体实现代码
<script> import { NatureStore } from "../../stores/nature"; import { BlooperStore } from "../../stores/bloopers"; import { NightStore } from "../../stores/night"; import { PortraitStore } from "../../stores/portrait"; import { PurpleStore } from "../../stores/purple"; import { UrbanStore } from "../../stores/urban"; import { UrbexStore } from "../../stores/urbex"; import { onDestroy } from "svelte"; export let params; let category = params.category; let pictures = []; let unsubscribe = null; // 建立category到对应store的映射表 const storeMap = { nature: NatureStore, bloopers: BlooperStore, night: NightStore, portrait: PortraitStore, purple: PurpleStore, urban: UrbanStore, urbex: UrbexStore }; // 响应式监听category变化,自动切换订阅 $: { // 先取消上一次的订阅,避免内存泄漏 if (unsubscribe) unsubscribe(); // 根据category获取目标store并订阅 const targetStore = storeMap[category]; if (targetStore) { unsubscribe = targetStore.subscribe(data => { pictures = data; }); } else { // 处理无效category的情况,比如清空数据 pictures = []; } } // 组件销毁时确保取消订阅 onDestroy(() => { if (unsubscribe) unsubscribe(); }); </script>
方案优势
- 简洁易维护:新增或删除store时,只需在
storeMap中修改一行代码,无需修改大量条件判断 - 响应式适配:自动监听路由参数
category的变化,实时切换订阅目标 - 内存安全:每次切换订阅前都会取消上一次的订阅,避免内存泄漏
进阶优化(可选)
如果store数量较多,可以把映射表抽离到单独文件统一管理:
// stores/storeRegistry.js import { NatureStore } from "./nature"; import { BlooperStore } from "./bloopers"; import { NightStore } from "./night"; // 导入其他store... export const storeMap = { nature: NatureStore, bloopers: BlooperStore, night: NightStore, // 其他映射关系... };
然后在组件中直接导入storeMap即可,进一步简化组件代码。
内容的提问来源于stack exchange,提问作者Eli-ott
相关产品推荐
相关产品推荐

