访问Salesforce资源

Lightning 组件可以访问全局 Salesforce 值,例如标签、资源和用户。

访问静态资源

从作用域模块导入静态资源。静态资源可以是存档(如 .zip 和 .jar 文件)、图像、样式表、JavaScript 和其他文件。@salesforce/resourceUrl

在导入静态资源之前,请先创建并上传文件。

创建并上传静态资源

要创建和上传静态资源,请执行以下操作:

  1. 在“设置”中,输入“快速查找”框,然后选择“静态资源”。Static Resources
  2. 单击“新建”。
  3. 在文本框中,输入用于标识 LWC 代码中的资源的文本。Name注意静态资源名称只能包含下划线和字母数字字符,并且在组织中必须是唯一的。它必须以字母开头,不能包含空格,不能以下划线结尾,也不能包含两个连续的下划线。
  4. 在文本区域中,指定资源的可选描述。Description
  5. 单击“浏览”导航到要上载的资源的本地副本。最大文件大小为 5 MB。一个组织最多可以有 250 MB 的静态资源。
  6. 设置用户会话,包括 API 和 Experience Cloud 用户会话:Cache Control
    • Private指定 Salesforce 服务器上缓存的静态资源数据不得与其他用户共享。静态资源仅存储在当前用户会话的缓存中。
    • Public指定缓存在 Salesforce 服务器上的静态资源数据与组织中的其他用户共享,以缩短加载时间。缓存后,所有 Internet 流量(包括未经身份验证的用户)都可以访问该资源。
  7. 点击保存

有关更多信息,请参阅 Salesforce 帮助:静态资源。

导入静态资源

使用此语法导入静态资源。

import myResource from "@salesforce/resourceUrl/resourceReference";
import myResource from "@salesforce/resourceUrl/namespace__resourceReference";
  • myResource– 引用静态资源的名称。
  • resourceReference– 静态资源的名称。
  • namespace– 如果静态资源位于托管包中,则此值为托管包的命名空间。

让我们看一些示例代码。

JavaScript 代码导入两个资源:Trailhead 徽标和 Trailhead 角色的图像。

// miscStaticResource.js
import { LightningElement } from "lwc";
import TRAILHEAD_LOGO from "@salesforce/resourceUrl/trailhead_logo";
import TRAILHEAD_CHARACTERS from "@salesforce/resourceUrl/trailhead_characters";

export default class MiscStaticResource extends LightningElement {
  // Expose the static resource URL for use in the template
  trailheadLogoUrl = TRAILHEAD_LOGO;

  // Expose URL of assets included inside an archive file
  einsteinUrl = TRAILHEAD_CHARACTERS + "/images/einstein.png";
}

静态资源可以是具有嵌套目录结构的存档文件。若要引用存档中的项目,请连接字符串以创建项目的路径,如示例中对 build .einsteinUrl

若要引用模板中的资源,请使用语法,该语法与用于引用任何 JavaScript 属性的语法相同。{property}

<!-- miscStaticResource.html -->
<template>
  <lightning-card title="MiscStaticResource" icon-name="custom:custom19">
    <div class="slds-m-around_medium">
      <img src={trailheadLogoUrl} />
      <img src={einsteinUrl} />
    </div>
  </lightning-card>
</template>

在 Salesforce DX 项目中,静态资源位于目录中。不能创建 的子目录。/force-app/main/default/staticresourcesstaticresources

为每个资源创建一个元数据文件。元数据文件定义资源的内容类型。.resource-meta

提示

此代码示例是 github.com/trailheadapps/lwc-recipes 存储库中的组件。miscStaticResource

访问内容资产文件

从作用域模块导入内容资产文件。将 Salesforce 文件转换为内容资产文件,以便在自定义应用程序和 Experience Builder 模板中使用该文件。@salesforce/contentAssetUrl

import myContentAsset from "@salesforce/contentAssetUrl/contentAssetReference";
import myContentAsset from "@salesforce/contentAssetUrl/namespace__contentAssetReference";
  • myContentAsset– 引用资源文件的名称。
  • contentAssetReference– 资源文件的名称。资产文件名只能包含下划线和字母数字字符,并且必须在您的组织中是唯一的。它必须以字母开头,不能包含空格,不能以下划线结尾,也不能包含两个连续的下划线。
  • namespace– 如果资源文件位于托管包中,则此值为托管包的命名空间。

让我们看一些示例代码。

JavaScript 代码导入两个内容资产文件。

// assetFileExample.js
import { LightningElement } from "lwc";
import SALES_WAVE_LOGO from "@salesforce/contentAssetUrl/SalesWaveLogo";
import PARTNER_LOGOS from "@salesforce/contentAssetUrl/PartnerLogos";

export default class AssetFileExample extends LightningElement {
  // Expose the asset file URL for use in the template
  salesWaveLogoUrl = SALES_WAVE_LOGO;

  // Expose URL of assets included inside an archive file
  goldPartnerLogoUrl = PARTNER_LOGOS + "pathinarchive=images/gold_partner.png";
}

内容资产文件可以是具有嵌套目录结构的存档文件。若要引用存档中的项目,请连接字符串以创建项目的路径,如示例中对 build .若要指定存档中内容资产文件的路径,请使用该参数。goldPartnerLogoUrlpathinarchive

若要引用模板中的资源,请使用语法,该语法与用于引用任何 JavaScript 属性的语法相同。{property}

<!-- assetFileExample.html -->
<template>
  <lightning-card title="Asset File Example" icon-name="custom:custom19">
    <div class="slds-m-around_medium">
      <img src={salesWaveLogoUrl} />
      <img src={goldPartnerLogoUrl} />
    </div>
  </lightning-card>
</template>

在 Salesforce DX 项目中,资产文件位于目录中。不能创建 的子目录。创建定义资产文件的元数据文件。/force-app/main/default/contentassetscontentassets.asset-meta

使用 SVG 资源

您可以通过两种方式将 SVG 资源添加到组件中。将其直接添加到组件的 HTML 模板中。将 SVG 资源作为静态资源上传,并将其导入到组件的 JavaScript 文件中。

SVG(可缩放矢量图形)是一种基于 XML 的图像格式,可用于定义线条、曲线、形状和文本。下面是一个文件示例,其中包含红色矩形、绿色圆圈和白色文本,上面写着“SVG”。

<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
    <rect width="100%" height="100%" fill="red"></rect>
    <circle cx="150" cy="100" r="80" fill="green"></circle>
    <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
</svg>

如您所见,每个形状都有一个标签,用于描述它是什么(例如,是一个矩形)、它的尺寸和颜色。rect

将 SVG 资源直接添加到 HTML 模板

若要在 HTML 模板中包含 SVG 资源,请像任何其他元素一样将其包含在标记中。<template>

<template>
    <svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
        <rect width="100%" height="100%" fill="red"></rect>
        <circle cx="150" cy="100" r="80" fill="green"></circle>
        <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
    </svg>
</template>

将 SVG 资源作为静态资源导入

  1. 在 SVG 文件中,向标记添加属性。id<svg><svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg" id="logo"> <rect width="100%" height="100%" fill="red"></rect> <circle cx="150" cy="100" r="80" fill="green"></circle> <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text> </svg>
  2. 将 SVG 资源作为静态资源上传到您的组织。
  3. 在组件的 JavaScript 文件中,导入静态资源。定义一个字段,该字段将对静态资源的引用与其 .id// myComponent.js import { LightningElement } from "lwc"; import SVG_LOGO from "@salesforce/resourceUrl/logo"; export default class myComponent extends LightningElement { svgURL = `${SVG_LOGO}#logo`; }
  4. 使用 SVG 元素引用 HTML 模板中的字段。<use><!-- myComponent.html --> <template> <svg xmlns="http://www.w3.org/2000/svg" width="300" height="200"> ; <use xlink:href={svgURL}></use> </svg> </template>

支持的SVG标签

Lightning Web 组件支持受限制的 SVG 标签列表。

  • <svg>
  • <a>
  • <altglyph>
  • <altglyphdef>
  • <altglyphitem>
  • <animatecolor>
  • <animatemotion>
  • <animatetransform>
  • <audio>
  • <canvas>
  • <circle>
  • <defs>
  • <desc>
  • <ellipse>
  • <filter>
  • <font>
  • <g>
  • <glyph>
  • <glyphref>
  • <hkern>
  • <image>
  • <line>
  • <lineargradient>
  • <marker>
  • <mask>
  • <mpath>
  • <path>
  • <pattern>
  • <polygon>
  • <polyline>
  • <radialgradient>
  • <rect>
  • <stop>
  • <switch>
  • <symbol>
  • <text>
  • <title>
  • <tref>
  • <tspan>
  • <video>
  • <view>
  • <vkern>
  • <use>

访问标签

从作用域模块导入标签。自定义标签是存储在 Salesforce 中的文本值,可以翻译成 Salesforce 支持的任何语言。使用自定义标签创建多语言应用程序,以用户的母语显示信息(例如,帮助文本或错误消息)。@salesforce/label

import labelName from "@salesforce/label/labelReference";
  • labelName– 引用标签的名称。
  • labelReference– 组织中标签的名称,格式为 。我们之所以使用这种格式,是因为它与托管软件包、Visualforce 和其他 Salesforce 技术中使用的格式相同。您可以使用相同的格式来访问标签,无论您在何处访问它们。namespace.labelNamemyns.labelName

此示例代码导入两个标签。

// labelExample.js
import { LightningElement } from "lwc";

// Import the URL for the static resource named 'salesforceLogo'
import SALESFORCE_LOGO from "@salesforce/resourceUrl/salesforceLogo";

// Import custom labels
import greeting from "@salesforce/label/c.greeting";
import salesforceLogoDescription from "@salesforce/label/c.salesforceLogoDescription";

export default class LabelExample extends LightningElement {
  // Expose the static resource URL to use in the template.
  logoUrl = SALESFORCE_LOGO;

  // Expose the labels to use in the template.
  label = {
    greeting,
    salesforceLogoDescription,
  };
}

若要在模板中使用标签,请使用与引用任何 JavaScript 属性相同的语法。{property}

<!-- labelExample.html -->
<template>
  <c-page-header
    header="Using static resources and custom labels"
    description="This sample shows how to reference external items like static resources and custom labels"
  ></c-page-header>

  <c-card>
    <img src={logoUrl} alt={label.salesforceLogoDescription} width="100" /><br />
    <br />
    {label.greeting}
  </c-card>
</template>

在 Salesforce DX 项目中,标签文件可以位于 的任何子目录中。例如,这个名为 的文件位于 中。force-app/main/defaultExampleLabels.labels-meta.xmlforce-app/main/default/mylabels

<?xml version="1.0" encoding="UTF-8"?>
<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
    <labels>
        <fullName>quoteManual</fullName>
        <value>This is a manual quote.</value>
        <language>en_US</language>
        <protected>false</protected>
        <shortDescription>Manual Quote</shortDescription>
    </labels>
    <labels>
        <fullName>quoteAuto</fullName>
        <value>This is an automatically generated quote.</value>
        <language>en_US</language>
        <protected>false</protected>
        <shortDescription>Automatic Quote</shortDescription>
    </labels>
</CustomLabels>

访问国际化属性

从作用域模块导入国际化属性。Lightning Web 组件具有国际化属性,您可以使用这些属性针对全球用户、跨语言、跨货币和时区调整组件。@salesforce/i18n

在单一货币组织中,Salesforce 管理员为其组织设置货币区域设置、默认语言、默认区域设置和默认时区。用户可以在其个人设置页面上设置其个人语言、区域设置和时区。

基本 Lightning 组件会自动适应运行它们的 Salesforce 组织的语言、区域设置和时区设置。若要国际化组件以便它们也适应,请使用国际化属性。

import internationalizationPropertyName from @salesforce/i18n/internationalizationProperty
  • internationalizationPropertyName– 引用国际化属性的名称。
  • internationalizationProperty– 国际化属性。

为当前用户返回属性值。

Internationalization 属性描述示例值
lang语言en-US
dir文本方向ltr
locale现场en-CA
defaultCalendar基于区域设置的默认日历格式Gregorian
defaultNumberingSystem基于区域设置的默认编号系统latn
calendarData用户区域设置的日历格式gregorian: {dayPeriods : {...}, days: {...}, eras: {...}, months: {...}, quarters: {...}}
currency货币代码CAD
firstDayOfWeek一周的第一天1
isEasternNameStyle指定名称是否遵循东方风格,例如,last name first name [middle] [suffix]
common.calendarData常见日历格式的补充日历数据。该值由 确定。defaultCalendargregorian:{calendarSystem:'solar',eras:{'0':{_end:'0-12-31'},'0':{_end:'1-01-01'}}}
common.digits数值的 Unicode 字符0123456789
dateTime.shortDateFormat短样式日期格式MM/dd/yyyy
dateTime.mediumDateFormat中型日期格式MMM d, yyyy
dateTime.longDateFormat长样式日期格式MMMM d, yyyy
dateTime.shortDateTimeFormat短样式日期时间格式MM/dd/yyyy h:mm a
dateTime.mediumDateTimeFormat中型日期时间格式MMM d, yyyy h:mm:ss a
dateTime.longDateTimeFormat长样式日期时间格式MMMM d, yyyy ‘at’ h:mm:ss a * z
dateTime.shortTimeFormat短样式时间格式h:mm a
dateTime.longTimeFormat长样式时间格式h:mmss a
number.currencyFormat货币格式#, ##0.00
number.currencySymbol货币符号$
number.decimalSeparator小数点分隔符.
number.exponentialSign指数符号E
number.groupingSeparator分组分隔符,
number.infinity无穷大符号
number.minusSign减号符号-
number.nan“不是数字”的字符串NaN
number.numberFormat数字格式#, ##0.###
number.perMilleSign每千个符号
number.percentFormat百分比格式#, ###0%
number.percentSign百分号符号%
number.plusSign加号符号+
number.superscriptExponentSign上标指数符号×
showJapaneseCalendar指定是否以日本英制日历格式显示日期
timeZone时区America/Los_Angeles

注意

对于 LWR 站点,and 映射到为站点配置的语言,并由浏览器的时区而不是用户的个人设置决定。 此外,不支持 、 和 。 如果更新了网站或组织语言配置,则必须重新发布网站。langlocaletimeZonecurrencynumber.currencySymbolnumber.currencyFormat

国际化值格式

国际化属性返回的值对应于 Unicode 区域设置数据标记语言 (LDML) 描述的格式。例如,遵循日历数据 LDML 规范。common.calendarData

示例:将日期格式化为本地化字符串

日期在不同语言中的格式不同。例如,美国使用月、日、年,如 2/15/19。英国使用日、月、年,如 15/2/19。

要根据用户的语言设置日期格式,请从模块导入用户的区域设置。若要设置日期格式,请使用 JavaScript 国际化 API。@salesforce/i18n/locale

// formatDate.js
import { LightningElement } from "lwc";
import LOCALE from "@salesforce/i18n/locale";

export default class FormatDate extends LightningElement {
  date = new Date(2020, 6, 7);
  formattedDate = new Intl.DateTimeFormat(LOCALE).format(this.date);
}
<!-- formatDate.html -->
<template> {formattedDate} </template>

或者,使用 lightning-formatted-date-time base 组件进行日期和时间格式设置。

示例:将数字格式化为本地化货币字符串

此示例使用 and 属性将数字格式化为本地化的货币字符串。localecurrency

// formatNumber.js
import { LightningElement } from "lwc";
import LOCALE from "@salesforce/i18n/locale";
import CURRENCY from "@salesforce/i18n/currency";

export default class FormatNumber extends LightningElement {
  number = 123456.78;
  formattedNumber = new Intl.NumberFormat(LOCALE, {
    style: "currency",
    currency: CURRENCY,
    currencyDisplay: "symbol",
  }).format(this.number);
}
<!-- formatNumber.html -->
<template> {formattedNumber} </template>

该对象定义货币输出。对于用户给定的区域设置,将数值显示为货币,并提供本地化的货币符号。Intl.NumberFormat

或者,将闪电格式的数字基组件用于数字、货币和百分比格式。

设置 HTML 属性

若要将国际化属性绑定到 HTML 属性,请将它们作为私有属性存储在组件的 JavaScript 文件中。在这里,确定用户的语言并指定文本在 HTML 中的显示方向。langdir

// languageExample.js
import { LightningElement } from "lwc";
import LANG from "@salesforce/i18n/lang";
import DIR from "@salesforce/i18n/dir";

export default class LanguageExample extends LightningElement {
  lang = LANG;
  dir = DIR;
}

在 HTML 模板中,使用 引用值。{property}

<!-- languageExample.html -->
<template>
  <p lang={lang} dir={dir}><!-- Localized text in a paragraph --></p>
</template>

获取有关当前用户的信息

若要获取有关当前用户的信息,请使用作用域模块。@salesforce/user

import property from "@salesforce/user/property";
  • property– 支持的属性包括 ,即用户的 ID,以及 ,这是一个布尔值,指示用户是否为访客用户。使用该属性检查用户是否在Experience Builder站点中进行了身份验证。IdisGuestisGuest

此示例代码导入当前用户 ID 并将其分配给属性以在 HTML 模板中提供访问权限。userId

// miscGetUserId.js
import { LightningElement } from "lwc";
import Id from "@salesforce/user/Id";

export default class MiscGetUserId extends LightningElement {
  userId = Id;
}

若要在模板中引用用户 ID,请使用语法,该语法与用于引用任何 JavaScript 属性的语法相同。{property}

<!-- miscGetUserId -->
<template>
  <lightning-card title="MiscGetUserId" icon-name="custom:custom19">
    <div class="slds-m-around_medium">
      <p>User Id:</p>
      {userId}
    </div>
  </lightning-card>
</template>

提示

此代码示例是 lwc-recipes 存储库中的组件。miscGetUserId

获取有关当前 Experience Builder 站点的信息

从和作用域模块导入有关当前 Experience Builder 站点的信息。@salesforce/community@salesforce/site

重要

如果组件导入 或 ,则它只能面向 Experience Builder 页面。您不能在任何其他 Salesforce 容器中使用该组件。请参阅为 Experience Builder 配置组件。@salesforce/community@salesforce/site

Experience Builder 站点由包含管理设置(如电子邮件和成员资格配置)的 Network 对象和包含域和页面设置信息的 Site 对象组成。使用该模块,您可以检索站点网络部分的 ID,而该模块允许您检索站点部分的 ID。@salesforce/community@salesforce/site

@salesforce/社区

从中导入当前 Experience Builder 站点的网络 ID 和基本路径。@salesforce/community

import propertyName from "@salesforce/community/property";
  • property– 支持的属性包括:
    • Id– 当前站点的 ID。例如,导入要作为参数传递给 API 的 ID。
    • basePath– 基本路径是位于域之后的站点 URL 部分。因此,如果您的网站域名是创建网站时添加的 URL 值,则网站的 URL 为 .在本例中,是基本路径。UniversalTelco.force.commyPartnerSiteUniversalTelco.force.com/myPartnerSite/smyPartnerSite/s例如,若要生成跨多个站点工作的链接组件,请导入基本路径并使用它来动态构造完整的站点 URL。
  • propertyName– 引用导入的 Experience Builder 属性的名称。

此示例代码调用一个 Apex 控制器,该控制器返回当前站点的所有源项。

// miscGetCommunityId.js
import { LightningElement } from "lwc";
import Id from "@salesforce/community/Id";
import getFeedElementPageForCommunity from "@salesforce/apex/CommunityFeedController.getFeedElementPageForCommunity";

export default class CommunityFeedElementPage extends LightningElement {
  @wire(getFeedElementPageForCommunity, { networkId: "$Id" })
  feedElementPage;
}

Apex 控制器采用社区 ID,以确保源结果的范围限定为该站点。

// CommunityFeedController.apex
public with sharing class CommunityFeedController {
    @AuraEnabled(cacheable=true)
    public static ConnectApi.FeedElementPage getFeedElementPageForCommunity(String networkId) {
    return ConnectApi.ChatterFeeds.getFeedElementsFromFeed(networkId, ConnectApi.FeedType.UserProfile,
        'me', 3, ConnectApi.FeedDensity.FewerUpdates, null, null,
        ConnectApi.FeedSortOrder.LastModifiedDateDesc, ConnectApi.FeedFilter.CommunityScoped);
    }
}

@salesforce/站点

从中导入当前 Experience Builder 站点的站点 ID 和活动语言列表。@salesforce/site

import propertyName from "@salesforce/site/property";
  • property– 支持的属性包括:
    • Id– 当前站点的 ID。例如,导入要作为参数传递给 API 的 ID。
    • activeLanguages– Experience Builder 站点中的活动语言列表包括默认站点语言和所有其他活动语言的元数据。您可以在Experience Builder的“设置”|”语言。非活动语言将被排除在列表中。返回值是语言对象的数组,其中每个对象都包含语言的标签和代码,例如 en-US。数组按标签的字母顺序排序。
  • propertyName– 引用导入的 Experience Builder 属性的名称。

此示例代码在语言选择器组件中使用。activeLanguages

// languagePicker.js
// Sample data: [{ code: 'en-US', label: 'English (US)' },{ code: 'fr', label: 'Françias' }]
import activeLanguages from "@salesforce/site/activeLanguages";

import { LightningElement } from "lwc";
import currentLanguage from "@salesforce/i18n/lang";
import basePath from "@salesforce/community/basePath";

export default class LanguagePicker extends LightningElement {
  get options() {
    return activeLanguages.map((x) => ({ value: x.code, ...x }));
  }

  get currentValue() {
    return currentLanguage;
  }

  handleLanguageSelect(evt) {
    const selectedLanguageCode = evt.detail.value;
    // locale is in base path and needs to be replaced with new locale
    const newBasePath = this.updateLocaleInBasePath(
      basepath,
      currentLanguage,
      selectedLanguageCode,
    );

    const currentUrl = window.location.pathname;
    if (currentUrl) {
      const restOfUrl = currentUrl.substring(basepath.length);
      window.location.href = window.location.origin + newBasePath + restOfUrl;
    } else {
      // WARNING: this is a current limitation of Lightning Locker in LWR sites
      // Locker must be disabled to reference the global window object
      console.warn(
        "Lightning Locker must be disabled for this language picker component to redirect",
      );
    }
  }

  updateLocaleInBasePath(path, oldLocale, newLocale) {
    if (path.endsWith("/" + oldLocale)) {
      // replace with new locale
      return path.replace(new RegExp("/" + oldLocale + "$"), "/" + newLocale);
    } else {
      // since the default locale is not present in the base path,
      // append the new locale
      return path + "/" + newLocale;
    }
  }
}

该组件使用 lightning-combobox 显示下拉语言选择器。

<!-- languagePicker.html -->
<template>
    <lightning-combobox
        options={options}
        value={currentValue}
        onchange={handleLanguageSelect}
    ></lightning-combobox>
</template>

检查权限

从 和 作用域模块导入 Salesforce 权限。根据上下文用户的权限自定义组件的行为。@salesforce/userPermission@salesforce/customPermission

提示

请参阅 lwc-recipes 存储库中的配方。miscPermissionBasedUI

要检查用户是否具有权限,请导入对该权限的静态引用,并评估它是 还是 。trueundefined

import hasPermission from "@salesforce/userPermission/PermissionName";

自定义权限可以包含命名空间。组织使用命名空间作为其自己的自定义和包的唯一标识符。如果自定义权限是从托管包安装的,请在权限名称前面加上命名空间,后跟。__

import hasPermission from "@salesforce/customPermission/PermissionName";
import hasPermission from "@salesforce/customPermission/namespace__PermissionName";

静态引用的名称由您选择。我们选择的格式是指示引用包含布尔值。has{Permission}

此示例检查当前用户是否具有 ViewSetup 标准权限。

// app.js
import { LightningElement } from 'lwc';
import hasViewSetup from '@salesforce/userPermission/ViewSetup';

export default class App extends LightingElement {
    get isSetupEnabled() {
        return !hasViewSetup;
    }

    openSetup(e) {...}
}

如果用户具有该权限,则会导致属性的计算结果为 ,因此不会禁用该按钮。!hasViewSetupdisabledfalse

<!-- app.html -->
<template>
  <setup-panel-group>
    <setup-button disabled={isSetupEnabled} onclick={openSetup}></setup-button>
  </setup-panel-group>
</template>

此示例检查当前用户是否具有从具有命名空间的托管包安装的 ViewReport 自定义权限。acme

// app.js
import { LightningElement } from "lwc";
import hasViewReport from "@salesforce/customPermission/acme__ViewReport";

export default class App extends LightingElement {
  get isReportVisible() {
    return hasViewReport;
  }
}

如果用户具有该权限,则组件将显示组件 。expense-report

<!--– app.html -->
<template>
  <common-view></common-view>

  <template lwc:if={isReportVisible}>
    <c-expense-report></c-expense-report>
  </template>
</template>

提示

将父 Aura 组件动态引用权限的任何情况替换为 Lightning Web 组件中的静态引用。静态引用效率更高,因为它不需要网络调用。

Access 客户端外形规格

若要访问运行浏览器的硬件的外形规格,请导入作用域模块。@salesforce/client/formFactor

import formFactorPropertyName from "@salesforce/client/formFactor";
  • formFactorPropertyName– 一个名称,指的是运行浏览器的硬件的外形规格。可能的值为:
    • Large– 桌面客户端。
    • Medium– 平板电脑客户端。
    • Small– 电话客户端。

将外形规格传递给电线适配器,以获取用于创建记录的默认布局和对象信息。getRecordCreateDefaults

import { getRecordCreateDefaults } from 'lightning/uiRecordApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import FORM_FACTOR from '@salesforce/client/formFactor';

@wire(getRecordCreateDefaults, { objectApiName: ACCOUNT_OBJECT, formFactor: FORM_FACTOR})
accountDefaults;