Skip to content

Svelte Counter Example

Trang này demo cách dùng Svelte component trong project Astro + Starlight.

Dưới đây là một Svelte component đơn giản (đã bị vô hiệu hóa trong Starlight MDX):

Counter.svelte
let count = 0;
function increment() { count += 1; }
<script>
let count = 0;
function increment() {
count += 1;
}
function decrement() {
count -= 1;
}
</script>
<div class="counter">
<button on:click={decrement}>-</button>
<span>{count}</span>
<button on:click={increment}>+</button>
</div>
  • client:load - Directive bắt buộc để Svelte component chạy JavaScript trên client
  • Starlight CSS variables - Component dùng --sl-color-* để match theme
  • Tự động scoped - CSS trong Svelte component chỉ apply cho component đó
  1. Reactive - State thay đổi tự động update UI
  2. Scoped CSS - Không lo xung đột style
  3. TypeScript support - Có thể dùng <script lang="ts">
  4. Small bundle - Svelte compile ra vanilla JS nhỏ gọn