3 回答

TA貢獻1911條經驗 獲得超7個贊
第 1 步:創建一個js返回true或的文件false(例如 util.js)
export function when(expression, truVal, falseVal) {
if (expression) {
return truVal();
}
if (falseVal) {
return falseVal();
}
return undefined;
}
第 2 步:js在您的文件中導入 util
import {
LitElement,
html
} from 'lit-element';
import {
when
} from 'util.js'
第 3 步:在isLoading. static get properties所以在初始加載時,我們設置onload為 trueconstructor
import {
LitElement,
html
} from 'lit-element';
import {
when
} from 'util.js'
class EmpComponent extends LitElement {
static get properties() {
return {
isLoading: {
type: Boolean
},
}
}
constructor() {
super();
this.isLoading = true;
}
第 4 步:一旦獲取數據,我們就可以渲染 DOM。然后我們可以設置isLoading為 false 然后使用渲染 DOMwhen
static get properties() {
return {
isLoading: {
type: Boolean
},
canRender: {
type: Boolean
}
}
}
constructor() {
super();
this.isLoading = true;
this.canRender = false;
this.data = this.getEmpData();
this.isLoading = false;
this.canRender = true;
}
render() {
return html `
${when(this.isLoading,() => html`<p>Loading...</p>`)}
${when(this.canRender,() => html`<your-component></your-component>`)}
`
}
這是until. 你可以從這個博客sabarinath blog獲得更多細節

TA貢獻1836條經驗 獲得超3個贊
解決方案
我評論了您應該進行更改的部分。你不需要對其他進口做奇怪的事情
import { LitElement, html } from 'lit-element';
class EmpComponent extends LitElement
{
constructor() {
super();
// you were returning a promise to an Array type...
// this.data = this.getEmpData();
// Correct
this.data = [];
this.getEmpData();
}
// ADD PROPS
static get properties() {
return {
data: {type:Array}
};
}
getEmpData() {
fetch('../../../emp-data.json')
.then(()=>(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// SET DATA ON RESOLVE
response.json().then(data => this.data = data);
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
}
render() {
<div>
$ {
(this.data || []).map(emp => emp.active ? this.dataTemplate(emp) : '')
}
</div>
}
}
customElements.define('emp-component', EmpComponent);

TA貢獻1789條經驗 獲得超8個贊
您沒有返回任何內容getEmpData()so this.datais undefined,因此出現錯誤。
請記住,如果您在調用return之前添加一個語句,那么將包含一個. 在這種情況下,該指令可以提供幫助:fetch()this.dataPromiseuntil
import {until} from 'lit-html/directives/until.js';
// ...
render() {
return html`
<div>
${until(
this.data.then(data => data.map(emp => emp.active ? this.dataTemplate(emp) : ''),
html`<p>Loading...</p>`,
)}
</div>
`;
}
添加回答
舉報