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

恭喜小主,贺喜小主,马上就大圆满了。 修炼完Key代码块就能突破到下个大境界了。 Key代码块会在key表达式改变时销毁和重建它所包含的小世界。有时候我们希望某个值发生变化时就重新执行转场,而不是只在所绑定元素被添加或移除时。 此时我们应该举个例子🌰:每次加载信息时,也就是i变化时,都播放打字机效果,我们可以把<p>元素包括在一个key代码块里:

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

Edit this page on GitHub

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