在 module
脚本块中导出的任何内容都会成为模块本身的导出。让我们导出一个 stopAll
函数:
AudioPlayer
<script module>
let current;
export function stopAll() {
current?.pause();
}
</script>
现在我们可以在 App.svelte
中导入 stopAll
...
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>
...并在事件处理程序中使用它:
App
<div class="centered">
{#each tracks as track}
<AudioPlayer {...track} />
{/each}
<button onclick={stopAll}>
stop all
</button>
</div>
你不能有默认导出,因为组件本身就是默认导出。
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>