【问题标题】:Fetching asynchronous data in a lit-element web component在 lit-element Web 组件中获取异步数据
【发布时间】:2020-07-02 10:48:31
【问题描述】:

我正在学习如何使用 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 组件中获取异步数据的最佳方式吗?

【问题讨论】:

    标签: ajax fetch web-component lit-element


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-01
      • 2020-02-02
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 2022-07-08
      相关资源
      最近更新 更多