Skip to main content
From 16:00 UTC on January 17, 2026, to 20:00 UTC on January 17, 2026, we will perform planned maintenance on the Trailhead, myTrailhead, and Trailblazer Community sites. During the maintenance, these sites will be unavailable, and users won't be able to access them. Please plan your activities around this required maintenance.

使用 Lightning Web 组件构建可重用 UI 组件

备注

备注

用中文(简体)学习?在中文(简体)Trailhead Playground 中开始挑战,用括号中提供的译文完成挑战。仅复制并粘贴英文值,因为挑战验证基于英文数据。如果在中文(简体)组织中没有成功通过挑战,我们建议您 (1) 将区域设置切换为美国,(2) 按此处说明将语言切换为英文,(3) 再次单击“检查挑战”按钮。

查看 Trailhead 本地化语言徽章详细了解如何利用 Trailhead 译文。

跟随 Trail Together 进行学习

进行这一步骤时,想要跟专家一起学习吗?观看此视频,它是 Trail Together 系列的一部分。

(此视频片段从 46:56 开始,方便您回放并再次观看步骤的开头部分。)

简介

Lightning web 组件是遵循 Web 组件标准的自定义 HTML 元素,采用 HTML 和现代 JavaScript 构建。Lightning web 组件 (LWC) 在浏览器本地运行,允许开发人员自定义现成的用户界面。

创建并部署 Lightning Web 组件

  • 在 force-app/main/default 下,右击 lwc 文件夹,选择 SFDX: Create Lightning Web Component(SFDX:创建 Lightning Web 组件)
  • 将 Lightning web 组件命名为 housingMap,并选择 main/default/lwc 目录。
  • 您会看到以下文件:一个 HTML 文件、一个 JavaScript 文件、一个元数据 XML 文件和一个 test.js 文件。
    创建新的 Lightning Web 组件 (LWC) 时创建的文件。
  • 在 HTML 文件 housingMap.html 中,复制并粘贴以下代码。
    <template>
  <lightning-card title="Housing Map">
    <!-- Explore all the base components via Base component library
    (https://developer.salesforce.com/docs/component-library/overview/components)-->
      <lightning-map map-markers={mapMarkers}> </lightning-map>
  </lightning-card>
</template>
备注

我们使用基本 Lightning 组件 lightning-map 在导图上绘制数据集。基本组件封装了许多功能。在本例中,您不需要编写 HTML 标记来生成导图 UI,也不需要编写太多的 JavaScript 代码来与 Google Maps 集成。

  • 保存文件。
  • 在 JavaScript 文件 housingMap.js 中,复制并粘贴以下代码。
import { LightningElement, wire } from "lwc";
import getHouses from "@salesforce/apex/HouseService.getRecords";
export default class HousingMap extends LightningElement {
    mapMarkers;
    error;
    @wire(getHouses)
    wiredHouses({ error, data }) {
        if (data) {
        console.log(data);
    }
  }
}
备注

Lightning web 组件调用您在上一节中编写的 Apex 类 HouseService 来获取数据。这段代码展示了如何通过使用 @wire 装饰器调用 Apex 方法来检索数据。

若要在 LWC 中使用 Apex 方法,请使用 @AuraEnabled 注释对其进行注释。您可以将 @AuraEnabled 方法作为函数导入 LWC(如第 2 行所示)。当与 @wire 装饰器一同使用时(第 8 行),该组件通过该方法检索数据。

接下来,让我们添加代码以根据 lightning-map 基本组件的需要转换数据。将 if (data) { 之后的代码替换为以下行。

// Use JavaScript Map function to transform the Apex method response wired to the component into the format required by lightning-map
          this.mapMarkers = data.map((element) => {
                return {
                    location: {
                        Street: element.Address__c,
                        City: element.City__c,
                        State: element.State__c
                    },
                    title: element.Name
                };
            });
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.mapMarkers = undefined;

housingMap.js 文件中的最终代码应如下所示。

import { LightningElement, wire } from "lwc";
import getHouses from "@salesforce/apex/HouseService.getRecords";
export default class HousingMap extends LightningElement {
    mapMarkers;
    error;
    @wire(getHouses)
    wiredHouses({ error, data }) {
        if (data) {
         // Use JavaScript Map function to transform the Apex method response wired to the component into the format required by lightning-map
          this.mapMarkers = data.map((element) => {
                return {
                    location: {
                        Street: element.Address__c,
                        City: element.City__c,
                        State: element.State__c
                    },
                    title: element.Name
                };
            });
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.mapMarkers = undefined;
        }
    }
}
  • 保存文件。
  • 在 XML 文件 housingMap.js-meta.xml 中,更改代码以匹配第 4-7 行。
    <?xml version="1.0" encoding="UTF-8"?>
    <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
     <apiVersion>59.0</apiVersion>
     <isExposed>true</isExposed>
      <targets>
     <target>lightning__HomePage</target>
    </targets>
    </LightningComponentBundle>
备注

请注意,我们将目标属性设置为 lightning__HomePage。这意味着管理员会将该组件放置在主页上。开发人员可以在此处添加其他目标,以显露 Salesforce UI 其他部分的组件。  有时,组件的目标包括额外的上下文,例如输入数据。记录页面上的记录 Id 值就是一个典型的例子。这里确定的目标决定了您的组件是否可以使用这些不同的上下文。在“资源”部分中了解其他目标类型的工作方式。

  • 保存文件。
  • 右击并选择 SFDX: Deploy This Source to Org(SFDX:将此源代码部署到组织)

将组件添加到应用程序主页

  • 在 Visual Studio Code 中,按 Ctrl+Shift+P (Windows) 或 Cmd+Shift+P (macOS/Linux) 打开命令面板。
  • 输入 SFDX
  • 选择 SFDX: Open Default Org(SFDX:打开默认组织)
    这会在单独的浏览器中打开 Trailhead Playground。
  • 单击 应用程序启动器,搜索并选择 Dreamhouse
  • 导航到主页选项卡:单击顶部导航菜单中的“主页”。
  • 单击 设置 然后选择 Edit Page(编辑页面)
  • housingMap Lightning web 组件从 Lightning 组件列表的自定义区域拖动到页面画布的顶部。
  • 单击 Save(保存)
  • 单击 Activate(激活)
  • 单击 Assign as Org Default(分配为组织默认设置)
  • 单击 Save(保存)
  • 再次单击 Save(保存),然后单击 返回 返回页面。
  • 刷新页面以查看新组件。

显示 Housing Map Lightning Web 组件的主页。

在 Salesforce 受管运行时使用 Lightning web 组件进行构建速度会更快,原因如下:

  • 您只需编写较少的代码即可通过访问许多基本 Lightning 组件来实现更多功能(如上面使用的 Housing Map 组件中的 lightning-map 和 lightning-card)。
  • 通过 JavaScript 装饰器(如上面代码中使用的 @wire 装饰器)和内置模块 (@salesforce/apex) 简化了客户端与后端 Apex 数据服务之间的连接。

这是一个非常简单的 LWC 示例。想看更高级的 Lightning web 组件示例吗?请查看 Trailhead 模块快速了解:探索 Dreamhouse 示例应用程序“了解应用程序示例”单元中构建 Property Explorer 页面所涉及的组件。在这里,我们使用 Lightning web 组件完全自定义了该应用程序的用户体验。

使用 Lightning Web 组件构建的自定义页面。

其他选择?安装并探索完整的 Dreamhouse 示例应用程序,以了解有关在 Salesforce Platform 上构建端到端应用程序的更多信息。

接下来做什么?

这个项目让您对作为一名开发人员如何使用 Salesforce Platform 的功能(如 LWC 和 Apex)有了大概的了解。然而,您能做的远不止这些! 

如果开发人员需要完全控制应用程序资源的水平和垂直扩充,则可以使用 Heroku 这款产品。Salesforce 产品套件和 Salesforce AppExchange 为您提供了无限的学习机会。

在这个学习旅程中,您不会孤单。在 Salesforce Trailblazer Community 的 Salesforce 开发人员小组中,与世界各地的其他开发人员合作、建立联系和学习 Salesforce 开发知识。

资源

在 Salesforce 帮助中分享 Trailhead 反馈

我们很想听听您使用 Trailhead 的经验——您现在可以随时从 Salesforce 帮助网站访问新的反馈表单。

了解更多 继续分享反馈