在我们迄今为止看到的所有示例中,<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):
<script module>
let current;
</script>
现在组件可以在没有任何状态管理的情况下相互 ‘talk’:
¥It’s now possible for the components to ‘talk’ to each other without any state management:
<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;
}}
/>
<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>