Svelte Counter Example
Svelte Component trong Astro
Section titled “Svelte Component trong Astro”Trang này demo cách dùng Svelte component trong project Astro + Starlight.
Counter Component
Section titled “Counter Component”Dưới đây là một Svelte component đơn giản (đã bị vô hiệu hóa trong Starlight MDX):
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>Giải thích
Section titled “Giải thích”- 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 đó
Lợi ích
Section titled “Lợi ích”- ✅ Reactive - State thay đổi tự động update UI
- ✅ Scoped CSS - Không lo xung đột style
- ✅ TypeScript support - Có thể dùng
<script lang="ts"> - ✅ Small bundle - Svelte compile ra vanilla JS nhỏ gọn