Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Store Subscriptions with $ | Stores and Shared State
Introduction to Svelte

Store Subscriptions with $

Swipe um das Menü anzuzeigen

Svelte makes working with stores much simpler through automatic store subscriptions. Instead of manually subscribing to store values, Svelte allows developers to access store data directly using the $ prefix.

This helps reduce repetitive code and keeps components easier to read.

Automatic Store Subscriptions

Normally, subscribing to reactive data requires additional setup. In Svelte, writable and derived stores can be accessed directly inside components using the $ syntax.

For example:

<script>
  import { count } from './stores/counterStore.js';
</script>

<h2>Total: {$count}</h2>

The $count value automatically stays synchronized with the store.

Whenever the store updates, the interface updates automatically as well.

Updating Store Values

The $ syntax can also update writable stores directly.

<button on:click={() => $count += 1}>
  Increase
</button>

When the button is clicked, the store value changes and the UI updates instantly.

Using Multiple Stores

Components can work with multiple stores at the same time.

<script>
  import { count } from './stores/counterStore.js';
  import { theme } from './stores/themeStore.js';
</script>

<h2>Count: {$count}</h2>
<h2>Theme: {$theme}</h2>

Svelte automatically keeps both values reactive.

question mark

What does the $ prefix do when working with Svelte stores?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 4. Kapitel 4

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 4. Kapitel 4
some-alt