Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

当表达式的值发生变化时,键块会销毁并重新创建其内容。如果你希望元素在值发生变化时播放其转换,而不是仅在元素进入或离开 DOM 时播放,则这很有用。

¥Key blocks destroy and recreate their contents when the value of an expression changes. This is useful if you want an element to play its transition whenever a value changes instead of only when the element enters or leaves the DOM.

例如,我们希望每当加载消息(即 i 发生变化)时,从 transition.js 播放 typewriter 转换。将 <p> 元素封装在一个关键块中:

¥Here, for example, we’d like to play the typewriter transition from transition.js whenever the loading message, i.e. i changes. Wrap the <p> element in a key block:

App
{#key i}
	<p in:typewriter={{ speed: 10 }}>
		{messages[i] || ''}
	</p>
{/key}
上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script>
	import { typewriter } from './transition.js';
	import { messages } from './loading-messages.js';
 
	let i = $state(-1);
 
	$effect(() => {
		const interval = setInterval(() => {
			i += 1;
			i %= messages.length;
		}, 2500);
 
		return () => {
			clearInterval(interval);
		};
	});
</script>
 
<h1>loading...</h1>
 
<p in:typewriter={{ speed: 10 }}>
	{messages[i] || ''}
</p>