在List-Element Web组件中获取异步数据 [英] Fetching asynchronous data in a lit-element web component

查看:54
本文介绍了在List-Element Web组件中获取异步数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用Fetch APILit-Element

获取Web组件中的异步数据
import {LitElement, html} from 'lit-element';

class WebIndex extends LitElement {

    connectedCallback() {
        super.connectedCallback();
        this.fetchData();

    }

    fetchData() {
        fetch('ajax_url')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                };
                response.json();
            })
            .then(data => {
                this.data = data;
                console.log('Success:', data);
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    }

    render() {
        if (!this.data) {
            return html`
                <h4>Loading...</h4>
            `;
        }
        return html`
            <h4>Done</h4>
        `;
    }

}

customElements.define('web-index', WebIndex);

但是,呈现的html从不更改。我做错了什么?这是在Web组件中提取异步数据的最佳方式吗?

推荐答案

您需要在组件属性中注册data,以便在更改数据值时调用呈现

static get properties() {
   return {
     data: Object
   }
}

https://lit-element.polymer-project.org/guide/properties

这篇关于在List-Element Web组件中获取异步数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆