如何在不调用update()的情况下获取Svelte自定义Store的内容?
问题
我希望调用Svelte自定义Store的函数来查询内容并返回结果,但不想调用update()方法——目前用update()返回原数值的写法太冗余,毕竟我根本不需要更新任何内容。
为说明问题,我基于Svelte自定义Store教程扩展了一个检查当前数值是否等于3的函数,代码如下:
App.svelte
<script> import { count } from './store.js'; </script> <h1>The count is {$count}</h1> <button on:click={count.increment}>+</button> <button on:click={count.decrement}>-</button> <button on:click={count.reset}>reset</button> <button on:click={count.three}>is it 3? (inside)</button>
store.js
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), three: () => update((n) => { console.log(n==3 ? 'yes' : 'no') return n }) }; } export const count = createCount();
是否可以不使用update()方法来重定义three函数?
解决方案
当然可以,以下几种方法能避免冗余的update()调用,更合理地实现查询逻辑:
方法1:在Store内部维护当前状态副本
创建Store时,通过订阅同步保存当前值的副本,后续查询直接使用该副本:
import { writable } from 'svelte/store'; function createCount() { let currentValue = 0; const { subscribe, set, update } = writable(currentValue); // 订阅Store,实时更新内部副本 subscribe(value => { currentValue = value; }); return { subscribe, increment: () => update(n => n + 1), decrement: () => update(n => n - 1), reset: () => set(0), three: () => { const result = currentValue === 3; console.log(result ? 'yes' : 'no'); return result; } }; } export const count = createCount();
方法2:使用get()函数直接获取当前值
svelte/store提供的get()方法可以直接读取Store的当前值,适合简单查询场景:
import { writable, get } from 'svelte/store'; function createCount() { const store = writable(0); const { subscribe, set, update } = store; return { subscribe, increment: () => update(n => n + 1), decrement: () => update(n => n - 1), reset: () => set(0), three: () => { const currentValue = get(store); const result = currentValue === 3; console.log(result ? 'yes' : 'no'); return result; } }; } export const count = createCount();
注意:get()会创建临时订阅,频繁调用可能有性能损耗,高频查询场景更推荐方法1。
方法3:一次性订阅获取值
如果不想依赖get(),可以通过临时订阅获取当前值后立即取消:
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), three: () => { const unsubscribe = subscribe(currentValue => { console.log(currentValue === 3 ? 'yes' : 'no'); unsubscribe(); }); } }; } export const count = createCount();
这种写法相对繁琐,仅在特殊场景下考虑使用。
内容的提问来源于stack exchange,提问作者Gertjan Kruiger
相关产品推荐
相关产品推荐

