Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and 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

前の演習では、ルーンを使用してコンポーネント内にリアクティブ性を追加しました。ただし、たとえばグローバル状態を共有する場合など、コンポーネントの 外部 でルーンを使用することもできます。

この演習の <Counter> コンポーネントはすべて、shared.js から counter オブジェクトをインポートします。ただし、これは通常のオブジェクトなので、ボタンをクリックしても何も起こりません。オブジェクトを $state(...) でラップします。

shared
export const counter = $state({
	count: 0
});

ここでエラーが発生します。通常の .js ファイルではルーンを使用できず、.svelte.js ファイルでのみ使用できるためです。これを修正するには、ファイルの名前を shared.svelte.js に変更します。

次に、Counter.svelte のインポート宣言を更新します。

Counter
<script>
	import { counter } from './shared.svelte.js';
</script>
<script lang="ts">
	import { counter } from './shared.svelte.js';
</script>

これで、いずれかのボタンをクリックすると、3 つすべてが同時に更新されます。

宣言が再割り当てされた場合(単に変更されるのではなく)、インポートする側がそれを知る方法がないため、モジュールから $state 宣言をエクスポートすることはできません。

Edit this page on GitHub

previous next
1
2
3
4
5
6
7
8
<script>
	import Counter from './Counter.svelte';
</script>
 
<Counter />
<Counter />
<Counter />