// 简单判断{#if user.loggedIn}<button on:click={toggle}>
Log out
</button>{/if}// 分支判断{#if user.loggedIn}<button on:click={toggle}>
Log out
</button>{:else}<button on:click={toggle}>
Log in</button>{/if}// 多分支判断{#if x >10}<p>{x} is greater than 10</p>{:elseif5> x}<p>{x} is less than 5</p>{:else}<p>{x} is between 5 and 10</p>{/if}
{@each a as arr}循环语句(类比vue列表渲染v-for),建议添加key值,Svelte将按照key值来进行想要的操作
<script>let cats =[{id:'J---aiyznGQ',name:'Keyboard Cat'},{id:'z_AbfPXTKms',name:'Maru'},{id:'OUtn3pvWmpg',name:'Henri The Existential Cat'}];</script><h1>The Famous Cats of YouTube</h1><ul>{#each cats as{ id, name }, i}<li><a target="_blank" href="https://www.youtube.com/watch?v={id}">{i +1}:{name}</a></li>{/each}</ul>// 绑定key{#each things asthing(thing.id)}<Thing current={thing.color}/>{/each}
await块(个人感觉实际使用频次不高,故简单介绍)
<script><script>let promise =getRandomNumber();asyncfunctiongetRandomNumber(){const res =awaitfetch(`tutorial/random-number`);const text =await res.text();if(res.ok){return text;}else{thrownewError(text);}}functionhandleClick(){
promise =getRandomNumber();}</script><button on:click={handleClick}>
generate random number
</button>{#await promise}<p>...waiting</p>{:then number}<p>The number is {number}</p>{:catch error}<p style="color: red">{error.message}</p>{/await}