我正在尝试维护一个Svelte商店的实时股票报价,以便屏幕上的出价和要价得到实时更新。我不确定如何组织存储以保持数据的响应性和有效性。数据来自websocket,如下所示:
{'symbol':'AAPL', 'bid':305.52, 'ask':305.55}
我的初始尝试如下所示:
import { readable, writable } from 'svelte/store';
export let quotes = {}
function addQuotes(sym) {
const quote = writable({
bid: 0,
ask: 0
});
quotes[sym] = quote;
}我想要做的是在整个SPA中有一个可用的报价映射,但每个单独的报价在每次更改时只更新它自己的符号,而不是整个页面。
这显然是错误的,但我不确定该怎么做。(这是我第一次使用Svelte。)
发布于 2020-01-10 17:44:58
你在正确的轨道上。
将股票价格作为散列存储在writable()存储中。
// in stores.js
export const stocks = writable({})然后,当您想要更新价格或添加新股票时,可以调用stocks.update()。
// in stores.js
export function update(symbol, data) {
// using `...` to destructure a copy, we don't want to overwrite previous value
stocks.update(({...records}) => {
// now update the copy
records[symbol] = data
// return the new value for the store, this will trigger updates in templates that subscribe
return records
})
}在.svelte组件中,导入store.js
<script>
import {stocks, update} from './store.js'
import {onMount} from 'svelte'
update('AAPL', {ask: 10, bid: 20})
update('MSFT', {ask: 10, bid: 20})
onMount(() => {
setTimeout(() => update('AAPL', {ask: 10.20, bid: 10.25}), 2000)
setTimeout(() => update('AAPL', {ask: 10.30, bid: 10.35}), 4000)
})
</script>
<!-- use dollar sign in front of store name to make svelte auto-subscribe -->
<pre>
{JSON.stringify($stocks, null, 2)}
</pre>https://stackoverflow.com/questions/59675481
复制相似问题