svelte教程(2)反應(yīng)性

Svelte的核心是功能強大的反應(yīng)系統(tǒng),用于使DOM與您的應(yīng)用程序狀態(tài)保持同步-例如,響應(yīng)事件。

<script>
    let count = 0;
    function handleClick() {
        count += 1;
    }
</script>
<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

聲明

當組件的狀態(tài)更改時,Svelte會自動更新DOM。通常,組件狀態(tài)的某些部分需要從其他部分計算并在它們發(fā)生任何變化時重新計算。使用$:聲明后只要任何引用的值發(fā)生更改,都要重新運行此代碼。
我們可以將他用作計算屬性。

<script>
    let count = 0;
    $: doubled = count * 2;
    
    function handleClick() {
        count+=1;
    }
</script>
<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<p>{count} doubled is {doubled}</p>

除此之外,我們可以反應(yīng)性的運行任意語句。

<script>
    let count = 0;
    $: doubled = count * 2;
    $: console.log(`the count is ${count}`)
    $: {
        console.log(`I SAID THE COUNT IS ${count}`);
    }
    $: if(count>=5){
        console.log(`count is dangerously high!`);
    }
    function handleClick() {
        count+=1;
    }
</script>
<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<p>{count} doubled is {doubled}</p>

注意:svelte的反應(yīng)性是由賦值觸發(fā)的,所以使用push、pop、splice、shift、unshift等數(shù)組操作不會導(dǎo)致更新。

<script>
  function add() {
    arr.push(arr[arr.length - 1] + 1);
  }
</script>
<button on:click={add}>add</button>
<p>The last one is {arr[arr.length - 1]}</p>

測試后發(fā)現(xiàn)并沒有觸發(fā)更新。
修改一下上面的add方法,如下:

<script>
  function add() {
    arr.push(arr[arr.length - 1] + 1);
    arr = arr;
  }
  // function add(){
  //    arr=[...arr,arr[arr.length-1]+1];
  // }
  // function add(){
  //    arr[arr.length]=arr[arr.length-1]+1;
  // }
</script>
<button on:click={add}>add</button>
<p>The last one is {arr[arr.length - 1]}</p>

本教程的所有代碼均上傳到github有需要的同學(xué)可以參考 https://github.com/sullay/svelte-learn

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容