Svelte 只讀 stores

2023-02-21 16:03 更新

并非所有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);
	};
});

示例代碼

  • App.svelte

<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>

  • stores.js

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);
	};
});


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)