onMount
onMount将在元件首次呈現到DOM之後運作。除了onDestroy之外,生命周期函數不會在SSR期間運作,這意味着一旦元件挂在到DOM上,我們就可以避免在DOM建構之前擷取到應在DOM建構以後加載的資料。
必須在逐漸初始化時調用生命周期函數,不能再setTimeout中調用。
如果onMount傳回一個函數,則在銷毀元件時将調用該函數。
<script>
import { onMount } from 'svelte';
let photos = [];
onMount(async () => {
const res = await fetch(`https://jsonplaceholder.typicode.com/photos?_limit=20`);
photos = await res.json();
});
</script>
<style>
.photos {
width: 100%;
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-gap: 8px;
}
figure, img {
width: 100%;
margin: 0;
}
</style>
<h1>Photo album</h1>
<div class="photos">
{#each photos as photo}
<figure>
<img src={photo.thumbnailUrl} alt={photo.title}>
<figcaption>{photo.title}</figcaption>
</figure>
{:else}
<!-- this block renders when photos.length === 0 -->
<p>loading...</p>
{/each}
</div>
通過測試發現onMount的回調函數執行順序在onDestroy之後。并且傳回不能是promise對象,也就意味着如果使用async關鍵字将不會在元件銷毀時執行。
<script>
import { onMount, onDestroy } from "svelte";
let photos = [];
onMount(() => {
fetch(`https://jsonplaceholder.typicode.com/photos?_limit=20`)
.then(res => {
return res.json();
})
.then(res => {
photos = res;
});
return () => {
console.log("onMount end2");
};
});
onDestroy(() => {
console.log("onDestroy2");
});
</script>
<style>
.photos {
width: 100%;
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-gap: 8px;
}
figure,
img {
width: 100%;
margin: 0;
}
</style>
<a href="/">Photo album</a>
<div class="photos">
{#each photos as photo}
<figure>
<img src={photo.thumbnailUrl} alt={photo.title} />
<figcaption>{photo.title}</figcaption>
</figure>
{:else}
<!-- this block renders when photos.length === 0 -->
<p>loading...</p>
{/each}
</div>
onDestory
當銷毀元件時調用。
<script>
import { onDestroy } from "svelte";
let seconds = 0;
const interval = setInterval(() => (seconds += 1), 1000);
onDestroy(() => clearInterval(interval));
</script>
<p>The page has been open for {seconds} {seconds === 1 ? 'second' : 'seconds'}</p>
beforeUpdate 、afterUpdate
beforeUpdate 在DOM更新前運作,afterUpdate 在DOM更新後運作。
<script>
import Eliza from 'elizabot';
import { beforeUpdate, afterUpdate } from 'svelte';
let div;
let autoscroll;
beforeUpdate(() => {
autoscroll = div && (div.offsetHeight + div.scrollTop) > (div.scrollHeight - 20);
});
afterUpdate(() => {
if (autoscroll) div.scrollTo(0, div.scrollHeight);
});
const eliza = new Eliza();
let comments = [
{ author: 'eliza', text: eliza.getInitial() }
];
function handleKeydown(event) {
if (event.which === 13) {
const text = event.target.value;
if (!text) return;
comments = comments.concat({
author: 'user',
text
});
event.target.value = '';
const reply = eliza.transform(text);
setTimeout(() => {
comments = comments.concat({
author: 'eliza',
text: '...',
placeholder: true
});
setTimeout(() => {
comments = comments.filter(comment => !comment.placeholder).concat({
author: 'eliza',
text: reply
});
}, 500 + Math.random() * 500);
}, 200 + Math.random() * 200);
}
}
</script>
<style>
.chat {
display: flex;
flex-direction: column;
height: 500px;
max-width: 320px;
margin: 0 auto;
}
.scrollable {
flex: 1 1 auto;
border-top: 1px solid #eee;
margin: 0 0 0.5em 0;
overflow-y: auto;
}
article {
margin: 0.5em 0;
}
.eliza{
text-align: left;
}
.user {
text-align: right;
}
span {
padding: 0.5em 1em;
display: inline-block;
}
.eliza span {
background-color: #eee;
border-radius: 1em 1em 1em 0;
}
.user span {
background-color: #0074D9;
color: white;
border-radius: 1em 1em 0 1em;
}
</style>
<div class="chat">
<h1>Eliza</h1>
<div class="scrollable" bind:this={div}>
{#each comments as comment}
<article class={comment.author}>
<span>{comment.text}</span>
</article>
{/each}
</div>
<input on:keydown={handleKeydown}>
</div>
tick
tick不同于其他生命周期,因為您可以随時調用它,而不僅是元件首次初始化時。它傳回一個promise,該promise在任何pending狀态的promise狀态更改并應用于DOM時立刻執行resolve。如果沒有pending狀态的promise時,則立即執行resolve。
當您在Svelte中更改元件狀态時,它不會立即更新DOM。而是等到下一個微任務,看看是否還有其他需要應用的更改,包括在其他元件中。這樣做避免了不必要的工作,并使浏覽器可以更有效地對事物進行批處理。
下面例子中使用tab切換大小寫,如不過不适用tick,由于text 更改後,dom并沒有馬上更新,是以立刻設定光标位置然後dom更新後失效。使用tick可以解決這個問題。
<script>
import { tick } from 'svelte';
let text = `Select some text and hit the tab key to toggle uppercase`;
async function handleKeydown(event) {
if (event.which !== 9) return;
event.preventDefault();
const { selectionStart, selectionEnd, value } = this;
const selection = value.slice(selectionStart, selectionEnd);
const replacement = /[a-z]/.test(selection)
? selection.toUpperCase()
: selection.toLowerCase();
text = (
value.slice(0, selectionStart) +
replacement +
value.slice(selectionEnd)
);
await tick();
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;
}
</script>
<style>
textarea {
width: 100%;
height: 200px;
}
</style>
<textarea value={text} on:keydown={handleKeydown}></textarea>
本教程的所有代碼均上傳到github有需要的同學可以參考
https://github.com/sullay/svelte-learn。