ajax - 在 lit-element Web 组件中获取异步数据

标签 ajax fetch web-component lit-element

我正在学习如何使用 fetch API 和 lit-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

关于ajax - 在 lit-element Web 组件中获取异步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62694623/

相关文章:

php - 在 php 中不加载/包含许多文件是否更快?

php - 在获取中使用变量

java - hibernate 不进行急切获取(使用获取 ="join"和惰性 ="false")

polymer 中的本地化?

javascript - 如何将 <li> 标签包裹在 <ul> 标签内

javascript - 如何在 ngx-image-cropper 上加载图像而不调用 imageChangedEvent 事件?

javascript - 在 jquery 中全局限制 $.ajax 请求

reactjs - 使用 Jest 测试 Redux thunk 中的调度操作

javascript - 如何在 Stencil.JS Web 组件中创建输入掩码?

angular - 将 Assets 翻译文件嵌入到 Angular Web 组件中