W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
并非所有stores
都需要在其他地方寫(xiě)入,比如,你可能有一個(gè)代表鼠標(biāo)位置或者用戶地理位置的stores
,這樣的stores
從其他地方寫(xiě)入并無(wú)意義,對(duì)于這種情況,我們有 只讀(readable) stores
。
點(diǎn)擊到 stores.js
選項(xiàng)卡, 第一個(gè)參數(shù) readable
可以一個(gè)是個(gè)初始值,也可以為 null
或 undefined
,第二個(gè)參數(shù)是 start
函數(shù),該函數(shù)有個(gè) set
回調(diào)方法,并返回一個(gè) stop
函數(shù)。 當(dāng)stores
首次被subscriber 時(shí)調(diào)用start
函數(shù),stop
則是最后當(dāng)subscriber被unsubscribes時(shí)調(diào)用。
export const time = readable(new Date(), function start(set) {
const interval = setInterval(() => {
set(new Date());
}, 1000);
return function stop() {
clearInterval(interval);
};
});
示例代碼
<script>
import { time } 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>
import { readable } from 'svelte/store';
export const time = readable(new Date(), function start(set) {
const interval = setInterval(() => {
set(new Date());
}, 1000);
return function stop() {
clearInterval(interval);
};
});
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)系方式:
更多建議: