首页 > 其他 > 详细

[Svelte 3] Use an onMount lifecycle method to fetch and render data in Svelte 3

时间:2019-05-21 23:30:37      阅读:118      评论:0      收藏:0      [点我收藏+]

Every Svelte 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.

In this lesson we‘re going to learn how to use onMount to fetch and render data from Star Wars API.

Doc: https://svelte.dev/docs#onMount

 

<script>
    import {onMount} from svelte;
    let people = []
    onMount(async () => {
        const response = await fetch(https://swapi.co/api/people/);
        const json = await response.json();
        people = json.results;

        return () => console.log(Destroyed);
    })
</script>

<ul>
    {#each people as {name, height, birth_year}}
        <li>
            <strong>{name}</strong>
            (height: {height}cm, birth year: {birth_year})
        </li>
    {:else}
        <p>loading...</p>
    {/each}
</ul>

 

[Svelte 3] Use an onMount lifecycle method to fetch and render data in Svelte 3

原文:https://www.cnblogs.com/Answer1215/p/10903054.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!