Skip to main content

你可以用 derived 函数创建一个依赖于 其他 一个或多个 store 的 store。接续上一个例子,我们可以创建一个 store,派生自页面打开的时间:

stores.js
export const elapsed = derived(
	time,
	($time) => Math.round(($time - start) / 1000)
);

也可以从多个输入 stores 中派生一个 store,然后显式地用 set 来设定其值而不是简单地返回(这在异步派生值的时候很有用)。查看 API 参考 获取更多信息。

Next: 自定义存储

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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>
 
initialising