響應式 let/var 宣告
在符文模式下,響應式狀態使用 $state
符文顯式宣告。
在舊版模式下,在元件頂層宣告的變數會自動被視為響應式。重新賦值或改變這些變數 (count += 1
或 object.x = y
) 將會導致 UI 更新。
<script>
let count = 0;
</script>
<button on:click={() => count += 1}>
clicks: {count}
</button>
由於 Svelte 的舊版模式響應性是基於賦值,因此使用陣列方法(如 .push()
和 .splice()
)不會自動觸發更新。需要後續的賦值才能「告訴」編譯器更新 UI。
<script>
let numbers = [1, 2, 3, 4];
function addNumber() {
// this method call does not trigger an update
numbers.push(numbers.length + 1);
// this assignment will update anything
// that depends on `numbers`
numbers = numbers;
}
</script>
上一頁 下一頁