W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
最后, <svelte:options>
標(biāo)簽允許你指定編譯器選項(xiàng)。
我們以 immutable
項(xiàng)為例。在本程序中,<Todo>
在接收新數(shù)據(jù)時(shí)會(huì)閃爍,點(diǎn)擊某一個(gè) done
就會(huì)更新todos
數(shù)據(jù)來切換狀態(tài), 就算其他 <Todo>
項(xiàng)沒有對DOM進(jìn)行更改,同樣會(huì)有閃爍效果出現(xiàn)。
我們可以設(shè)置<Todo>
組件,讓其期望的數(shù)據(jù)是不可變(immutable) 的。 這意味著我們承諾永遠(yuǎn)不會(huì)對“todo”的屬性進(jìn)行“變更(mutate )”,而是在內(nèi)容發(fā)生變化時(shí)重新創(chuàng)建新的todo對象。
將此代碼添加到Todo.svelte
文件內(nèi)頂部:
<svelte:options immutable={true}/>
您可以根據(jù)需要將其簡寫為 ?
<svelte:options immutable/>
? :
現(xiàn)在,當(dāng)您通過單擊todo來切換狀態(tài)時(shí),僅被更新的組件會(huì)閃爍:
該標(biāo)簽可設(shè)置的選項(xiàng)有:
immutable={true}
:你不能使用可變數(shù)據(jù),因此編譯器可以通過引用簡單的對比檢查來確定值是否已更改。immutable={false}
:默認(rèn)值。對于可變對象數(shù)據(jù)變更,Svelte將其保持不變。accessors={true}
:為組件的屬性添加getter和setter。accessors={false}
:默認(rèn)。namespace="..."
:將使用namespace的組件,最常見的是"svg"
。tag="..."
:指定將此組件編譯為自定義標(biāo)簽時(shí)使用的名稱。
有關(guān)這些選項(xiàng)的更多信息,請查閱 API reference 。
示例代碼
<script>
import Todo from './Todo.svelte';
let todos = [
{ id: 1, done: true, text: 'wash the car' },
{ id: 2, done: false, text: 'take the dog for a walk' },
{ id: 3, done: false, text: 'mow the lawn' }
];
function toggle(toggled) {
todos = todos.map(todo => {
if (todo === toggled) {
// return a new object
return {
id: todo.id,
text: todo.text,
done: !todo.done
};
}
// return the same object
return todo;
});
}
</script>
<h2>Todos</h2>
{#each todos as todo}
<Todo {todo} on:click={() => toggle(todo)}/>
{/each}
<svelte:options immutable={true}/>
<script>
import { afterUpdate } from 'svelte';
import flash from './flash.js';
export let todo;
let div;
afterUpdate(() => {
flash(div);
});
</script>
<style>
div {
cursor: pointer;
line-height: 1.5;
}
</style>
<!-- the text will flash red whenever
the `todo` object changes -->
<div bind:this={div} on:click>
{todo.done ? '??': ''} {todo.text}
</div>
export default function flash(element) {
requestAnimationFrame(() => {
element.style.transition = 'none';
element.style.color = 'rgba(255,62,0,1)';
element.style.backgroundColor = 'rgba(255,62,0,0.2)';
setTimeout(() => {
element.style.transition = 'color 1s, background 1s';
element.style.color = '';
element.style.backgroundColor = '';
});
});
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: