我正在阅读 Svelte 教程,并且在自定义商店页面 ( https://svelte.dev/tutorial/custom-stores ) 上。示例代码是使用工厂函数编写的,该函数createCount
被立即调用以创建导出的存储对象:
import { writable } from 'svelte/store';
function createCount() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1),
decrement: () => update(n => n - 1),
reset: () => set(0)
};
}
export const count = createCount();
这样做的原因是什么,而不是像这样直接导出 store 对象:
import { writable } from 'svelte/store';
const { subscribe, set, update } = writable(0);
export const count = {
subscribe,
increment: () => update(n => n + 1),
decrement: () => update(n => n - 1),
reset: () => set(0)
};