Med*_*ist 5 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);
Run Code Online (Sandbox Code Playgroud)
然而呈现的html永远不会改变。我做错了什么?这是在 Web 组件中获取异步数据的最佳方式吗?
小智 4
您需要data在组件属性中注册,以便在数据值更改后调用渲染
static get properties() {
return {
data: Object
}
}
Run Code Online (Sandbox Code Playgroud)
https://lit.dev/docs/components/properties/
| 归档时间: |
|
| 查看次数: |
7356 次 |
| 最近记录: |