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

在我们迄今为止看到的所有示例中,<script> 块包含在初始化每个组件实例时运行的代码。对于绝大多数组件,这就是你所需要的。

¥In all the examples we’ve seen so far, the <script> block contains code that runs when each component instance is initialised. For the vast majority of components, that’s all you’ll ever need.

偶尔,你需要在单个组件实例之外运行一些代码。例如:从 上一练习 返回到我们的自定义音频播放器,你可以同时播放所有四个音轨。如果播放一个会停止所有其他的,那就更好了。

¥Very occasionally, you’ll need to run some code outside of an individual component instance. For example: returning to our custom audio player from a previous exercise, you can play all four tracks simultaneously. It would be better if playing one stopped all the others.

我们可以通过声明 <script module> 块来做到这一点。其中包含的代码将在模块首次评估时运行一次,而不是在实例化组件时运行。将其放在 AudioPlayer.svelte 的顶部(请注意,这是一个单独的脚本标记):

¥We can do that by declaring a <script module> block. Code contained inside it will run once, when the module first evaluates, rather than when a component is instantiated. Place this at the top of AudioPlayer.svelte (note that this is a separate script tag):

AudioPlayer
<script module>
	let current;
</script>

现在组件可以在没有任何状态管理的情况下相互 ‘talk’:

¥It’s now possible for the components to ‘talk’ to each other without any state management:

AudioPlayer
<audio
	src={src}
	bind:currentTime={time}
	bind:duration
	bind:paused
	onplay={(e) => {
		const audio = e.currentTarget;

		if (audio !== current) {
			current?.pause();
			current = audio;
		}
	}}
	onended={() => {
		time = 0;
	}}
/>
上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
	import AudioPlayer from './AudioPlayer.svelte';
	import { tracks } from './tracks.js';
</script>
 
<div class="centered">
	{#each tracks as track}
		<AudioPlayer {...track} />
	{/each}
</div>
 
<style>
	.centered {
		display: flex;
		flex-direction: column;
		height: 100%;
		justify-content: center;
		gap: 0.5em;
		max-width: 40em;
		margin: 0 auto;
	}
</style>