相关疑难解决方法(0)

在 lit-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);
Run Code Online (Sandbox Code Playgroud)

然而呈现的html永远不会改变。我做错了什么?这是在 Web 组件中获取异步数据的最佳方式吗?

ajax fetch web-component lit-element

5
推荐指数
1
解决办法
7356
查看次数

标签 统计

ajax ×1

fetch ×1

lit-element ×1

web-component ×1