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

<script module>还支持导出哦,比如我们可以在AudioPlayer.svelte里导出函数stopAll:

Anything exported from a module script block becomes an export from the module itself. Let’s export a stopAll function:

AudioPlayer
<script module>
	let current;

	export function stopAll() {
		current?.pause();
	}
</script>

然后就可以在App.svelte里引入函数stopAll了:

We can now import stopAll in App.svelte...

App
<script>
	import AudioPlayer, { stopAll } from './AudioPlayer.svelte';
	import { tracks } from './tracks.js';
</script>
<script lang="ts">
	import AudioPlayer, { stopAll } from './AudioPlayer.svelte';
	import { tracks } from './tracks.js';
</script>

在事件处理器里使用stopAll:

...and use it in an event handler:

App
<div class="centered">
	{#each tracks as track}
		<AudioPlayer {...track} />
	{/each}

	<button onclick={stopAll}>
		stop all
	</button>
</div>

另外需要注意的是导出没有默认值,因为组件本身就是默认导出

You can’t have a default export, because the component is the default export.

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