W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
最后, <svelte:options>
標簽允許你指定編譯器選項。
我們以 immutable
項為例。在本程序中,<Todo>
在接收新數(shù)據(jù)時會閃爍,點擊某一個 done
就會更新todos
數(shù)據(jù)來切換狀態(tài), 就算其他 <Todo>
項沒有對DOM進行更改,同樣會有閃爍效果出現(xiàn)。
我們可以設置<Todo>
組件,讓其期望的數(shù)據(jù)是不可變(immutable) 的。 這意味著我們承諾永遠不會對“todo”的屬性進行“變更(mutate )”,而是在內容發(fā)生變化時重新創(chuàng)建新的todo對象。
將此代碼添加到Todo.svelte
文件內頂部:
<svelte:options immutable={true}/>
您可以根據(jù)需要將其簡寫為 ?
<svelte:options immutable/>
? :
現(xiàn)在,當您通過單擊todo來切換狀態(tài)時,僅被更新的組件會閃爍:
該標簽可設置的選項有:
immutable={true}
:你不能使用可變數(shù)據(jù),因此編譯器可以通過引用簡單的對比檢查來確定值是否已更改。immutable={false}
:默認值。對于可變對象數(shù)據(jù)變更,Svelte將其保持不變。accessors={true}
:為組件的屬性添加getter和setter。accessors={false}
:默認。namespace="..."
:將使用namespace的組件,最常見的是"svg"
。tag="..."
:指定將此組件編譯為自定義標簽時使用的名稱。
有關這些選項的更多信息,請查閱 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號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: