Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

贴心的Svelte还提供了些响应式类(reactive classes), 对应JavaScript中的相应类:Map, Set, Date, URL, URLSearchParams. 比如我们可能会使用$state(new Date())声明一个date变量,并在setInterval中重新赋值。还可以使用svelte/reactivity提供的SvelteDate:

Svelte ships with several reactive classes that you can use in place of JavaScript built-in objects — namely Map, Set, Date, URL and URLSearchParams. In this exercise, we could declare date using $state(new Date()) and reassign it inside the setInterval. But a nicer alternative is to use SvelteDate from svelte/reactivity:

App
<script>
	import { SvelteDate } from 'svelte/reactivity';

	let date = new SvelteDate();

	// ...
</script>
<script lang="ts">
	import { SvelteDate } from 'svelte/reactivity';

	let date = new SvelteDate();

	// ...
</script>

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>
	let date = new Date();
 
	const pad = (n) => n < 10 ? '0' + n : n;
 
	$effect(() => {
		const interval = setInterval(() => {
			date.setTime(Date.now());
		}, 1000);
 
		return () => {
			clearInterval(interval);
		};
	});
</script>
 
<p>The time is {date.getHours()}:{pad(date.getMinutes())}:{pad(date.getSeconds())}</p>