我正在学习如何使用 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/