zoukankan      html  css  js  c++  java
  • [Svelte 3] Use an onMount lifecycle method to fetch and render data in Svelte 3

    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>
  • 相关阅读:
    二人组
    对于软件工程的理解
    shell 远程链接
    shell变量
    shell教程
    正则表达式--练习
    git--版本库
    git-版本回退
    git--时光穿梭
    git安装
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10903054.html
Copyright © 2011-2022 走看看