![](https://img.haomeiwen.com/i21032798/f594e02a961a6524.png)
onMount
Every component has a lifecycle that starts when it is created, and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle. The one you'll use most frequently is onMount
, which runs after the component is first rendered to the DOM.
<script>
import { onMount } from 'svelte';
onMount(() => {
console.log('the component has mounted');
});
</script>
If the onMount
callback returns a function, that function will be called when the component is destroyed.
beforeUpdate and afterUpdate
The beforeUpdate
function schedules work to happen immediately before the DOM is updated. afterUpdate
is its counterpart, used for running code once the DOM is in sync with your data.
Together, they're useful for doing things imperatively that are difficult to achieve in a purely state-driven way, like updating the scroll position of an element.
import {
beforeUpdate,
afterUpdate
} from 'svelte';
beforeUpdate(() => {
});
afterUpdate(() => {
});
tick
The tick
function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises(初始化). It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).
When you update component state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next microtask to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively.
<script>
import { tick } from 'svelte';
let text = `Select some text and hit the tab key to toggle uppercase`;
async function handleKeydown(event) {
if (event.key !== 'Tab') 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>
<textarea
value={text}
on:keydown={handleKeydown}
/>
<style>
textarea {
width: 100%;
height: 100%;
resize: none;
}
</style>
网友评论