阅读(2002) (0)

Svelte 只读 stores

2023-02-21 16:02:12 更新

并非所有stores都需要在其他地方写入,比如,你可能有一个代表鼠标位置或者用户地理位置的stores,这样的stores从其他地方写入并无意义,对于这种情况,我们有 只读(readable) stores

点击到 stores.js 选项卡, 第一个参数 readable可以一个是个初始值,也可以为 null 或 undefined ,第二个参数是 start 函数,该函数有个 set 回调方法,并返回一个 stop函数。 当stores首次被subscriber 时调用start函数,stop则是最后当subscriber被unsubscribes时调用。

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