codecamp

Svelte stores派生

你可以创建一个stores,其内的值可以派生(derived)于一个或多个 其他 stores。在前面的示例的基础上,我们可以创建派生时间到其他页面:

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

可以从多个源派生​stores​, 并显式用​​set​​指定它的值而不是返回它(这对异步调用的派生值很有用)。 更多请查阅API 参考 。

示例代码

  • App.svelte

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

  • stores.js

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


Svelte 只读 stores
Svelte 自定义 stores
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Svelte module context

Svelte 调试

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }