在Salesforce LWC中调用Apex时显示加载指示器



在Lightning Web组件中从Apex检索数据时,显示加载指示符的最佳方式是什么?

我有这样的方法:

import { LightningElement, api } from "lwc";
import shouldShowCard from "@salesforce/apex/ApexClass.shouldShowCard";
/**
* Card component that is conditionally shown based on Apex.
*/
export default class ConditionalCard extends LightningElement {
@api recordId;
@api isDone = false;
@api shouldShow = false;
connectedCallback() {
shouldShowCard({ id: this.recordId })
.then(result => {
this.shouldShow = result;
})
.finally(() => {
this.isDone = true;
});
}
}

这个HTML

<template>
<template if:false={isDone}>
<div>Loading...</div>
</template>
<template if:true={shouldShow>
<div>Card</div>
</template>
</template>

现在,这是可行的,但我使用的是LWC ESLint规则,当我这样做时,我会收到一个错误/警告"没有api重新分配",因为我正在connectedCallback中分配api属性。https://github.com/salesforce/eslint-plugin-lwc/blob/master/docs/rules/no-api-reassignments.md

这似乎是合理的,尽管它与Salesforce Lightning Spinner显示的模式非常相似。https://developer.salesforce.com/docs/component-library/bundle/lightning-spinner/documentation

所以我只是在寻找处理这个问题的最佳方法的建议,或者我是否应该禁用ESLint规则。其他需要考虑的事情是如何测试这些东西,与API装饰器的反应性让我很容易,但如果我不使用最好的方法,我不想继续。

如果这些参数是内部状态,如果您不打算从父组件设置它们或将它们公开给系统管理员,以便他可以在Lightning App Builder中配置组件,则不需要@api。您应该可以只使用@track,甚至根本不使用注释。对于简单的变量,您不需要自Spring’20以来的@track(发行说明(;如果您的变量是数组或对象,您可能仍然需要它。

这应该能很好地让ESLint安静下来。

我做得有点不同,我想是Visualforcestatusrendered天的个人偏好。

<template>
<template if:true={loaded}>
<p>Content goes here</p>
</template>
<template if:false={loaded}>
<lightning-spinner variant="brand" alternative-text="Loading"></lightning-spinner>
</template>
</template>

import { LightningElement, api, wire, track } from 'lwc';
import someMethod from '@salesforce/apex/SomeClass.someMethod';
export default class StackExample extends LightningElement {
@api recordId;
@track data;
loaded = false;
@wire(someMethod, { i: '$recordId' }) wiredResponse({ error, data }) {
if (data) {
this.data = data;
// some post-processing here
} else if (error) {
// show toast?
}
if(data || error){
this.loaded = true;
}
}
}

请记住,像<lightning-datatable>这样的一些标签具有内部微调器。在文档中搜索isLoading。因此,您甚至不需要html中的if

最新更新