美文网首页
Getting started with Svelte - Li

Getting started with Svelte - Li

作者: 游文影月志 | 来源:发表于2023-11-28 16:33 被阅读0次

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>

相关文章

网友评论

      本文标题:Getting started with Svelte - Li

      本文链接:https://www.haomeiwen.com/subject/wuozwdtx.html