W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
你可以創(chuàng)建一個(gè)stores
,其內(nèi)的值可以派生(derived)于一個(gè)或多個(gè) 其他 stores
。在前面的示例的基礎(chǔ)上,我們可以創(chuàng)建派生時(shí)間到其他頁面:
export const elapsed = derived(
time,
$time => Math.round(($time - start) / 1000)
);
可以從多個(gè)源派生?
stores
?, 并顯式用??set
??指定它的值而不是返回它(這對(duì)異步調(diào)用的派生值很有用)。 更多請(qǐng)查閱API 參考 。
示例代碼
<script>
import { time, elapsed } from './stores.js';
const formatter = new Intl.DateTimeFormat('en', {
hour12: true,
hour: 'numeric',
minute: '2-digit',
second: '2-digit'
});
</script>
<h1>The time is {formatter.format($time)}</h1>
<p>
This page has been open for
{$elapsed} {$elapsed === 1 ? 'second' : 'seconds'}
</p>
import { readable, derived } from 'svelte/store';
export const time = readable(new Date(), function start(set) {
const interval = setInterval(() => {
set(new Date());
}, 1000);
return function stop() {
clearInterval(interval);
};
});
const start = new Date();
export const elapsed = derived(
time,
$time => Math.round(($time - start) / 1000)
);
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: