快速操作

快速操作使用户能够在 Salesforce 中执行更多操作。通过自定义快速操作,您可以方便地访问最重要的信息,从而使用户的导航和工作流程尽可能顺畅。快速操作可以在记录页面上调用自定义 Lightning Web 组件。

配置组件时,可以选择在模式窗口中显示它,也可以选择无头执行其自定义代码。例如,快速操作可以打开自定义 Lightning Web 组件,其中包含允许用户创建或更新记录上特定字段的表单。快速操作还可以执行导航到另一个页面或调度事件的 Lightning Web 组件代码。

注意

Lightning Web 组件仅支持作为 Lightning Experience 中的快速操作。Salesforce 移动应用程序不支持使用 Lightning Web 组件作为快速操作。

配置组件以执行快速操作

要使用 Lightning Web 组件作为快速操作,请定义组件的元数据。

屏幕快速操作和无头快速操作

LWC 快速操作有两种类型:屏幕快速操作和无头快速操作

  • 屏幕快速操作在模式窗口中显示组件。请参阅创建屏幕快速操作。
  • 无外设快速操作执行您在方法中提供的自定义代码。请参阅创建 Headless 快速操作。@api invoke()

注意

您只能将 Lightning Web 组件用作记录页面上的快速操作。您不能将 Lightning Web 组件用作全局快速操作。

在配置文件中定义组件元数据

组件的项目文件夹必须包含定义组件元数据值的 componentName.js-meta.xml 配置文件。若要将组件用作快速操作,请按照以下步骤配置文件。

  1. 在 中,添加为 a 以将 Lightning Web 组件指定为记录页面上的快速操作。targetslightning__RecordActiontarget
  2. 添加 并设置为 。targetConfigtargetslightning__RecordAction
  3. 设置为 或 选择快速操作类型。如果未指定 ,则快速操作默认为屏幕操作。actionTypeScreenActionActionactionType

此配置文件定义屏幕操作。

<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  <apiVersion>52.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__RecordAction</target>
  </targets>
  <targetConfigs>
    <targetConfig targets="lightning__RecordAction">
      <actionType>ScreenAction</actionType>
    </targetConfig>
  </targetConfigs>
</LightningComponentBundle>

此配置文件定义了无头操作。

<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  <apiVersion>52.0</apiVersion>
  <isExposed>true</isExposed>
  <targets>
    <target>lightning__RecordAction</target>
  </targets>
  <targetConfigs>
    <targetConfig targets="lightning__RecordAction">
      <actionType>Action</actionType>
    </targetConfig>
  </targetConfigs>
</LightningComponentBundle>

请参阅 XML 配置文件元素的完整列表。

在 Salesforce 设置中创建快速操作

在 Salesforce 设置中,通过“对象管理器”页面创建特定于对象的操作。然后将该操作添加到页面布局的 Salesforce Mobile 和 Lightning Experience 操作部分。请参阅 Salesforce 帮助中的快速操作。

注意

Salesforce 移动应用程序不支持使用 Lightning Web 组件作为快速操作。

创建屏幕快速操作

屏幕快速操作将显示在模式窗口中。提供您自己的标记或使用该组件,以实现基于 Lightning Design System 的一致用户界面。lightning-quick-action-panel

要使组件用作屏幕快速操作,请配置目标。请参阅配置组件以执行快速操作。

与记录页面上的其他 Lightning Web 组件不同,LWC 快速操作不会传入 .如果需要访问 ,请在代码中设置 的值。recordIdconnectedCallback()recordIdrecordId

_recordId;
set recordId(recordId) {
    if (recordId !== this._recordId) {
        this._recordId = recordId;

打开和关闭模式窗口

屏幕快速操作可在模式窗口中打开 Lightning Web 组件。要以编程方式关闭模式窗口,例如,要创建“取消”按钮,请生成调度自定义事件的 UI。从模块导入事件。CloseActionScreenEventlightning/actions

import { CloseActionScreenEvent } from "lightning/actions";

以下各节包含完整的代码示例。

注意

如果使用自定义页脚按钮构建屏幕快速操作,则按 X 仅关闭模式,则没有挂钩在关闭时执行其他逻辑。如果屏幕快速操作具有在“取消”时执行的逻辑,则在面板关闭时将绕过该逻辑。

使用 lightning-quick-action-panel 实现一致的 UI

要提供一致的 Salesforce UI,请将 Lightning Web 组件包装在 lightning-quick-action-panel 组件中,该组件提供与 Salesforce Lightning Design System 中的模式蓝图一致的页眉、正文和页脚。

<template>
  <lightning-quick-action-panel header="My action">
    Here's some content for the modal body.

    <div slot="footer">
      <lightning-button variant="neutral" label="Cancel"></lightning-button>
      <lightning-button variant="brand" label="Save" class="slds-m-left_x-small"></lightning-button>
    </div>
  </lightning-quick-action-panel>
</template>

在模态主体中创建表单

创建模态主体的一种方法是将组件与由组件填充的字段值一起使用。取消和提交按钮必须嵌套在组件中,因此使用此方法时不需要页脚槽。lightning-record-edit-formlightning-input-fieldlightning-record-edit-form

本示例创建一个窗体,用于填充不带页脚的 name 和 phone 字段。它呈现一个模态窗口,其标题包含文本“编辑字段操作”。lightning-record-edit-form

<template>
  <lightning-quick-action-panel header="Edit Fields Action">
    <lightning-record-edit-form
      record-id={recordId}
      object-api-name={objectApiName}
      onsuccess={handleSuccess}>
      <lightning-input-field field-name="Name"></lightning-input-field>
      <lightning-input-field field-name="Phone"></lightning-input-field>
      <lightning-button variant="neutral" label="Cancel"></lightning-button>
      <lightning-button variant="brand" class="slds-m-left_x-small" label="Save" type="submit">
      </lightning-button>
    </lightning-record-edit-form>
  </lightning-quick-action-panel>
</template>

当用户单击提交按钮时,将调用事件处理程序。处理程序使用该函数关闭模式窗口。handleSuccessCloseActionScreenEvent

import { LightningElement, api } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { CloseActionScreenEvent } from "lightning/actions";

export default class QuickEditFormExample extends LightningElement {
  @api recordId;
  @api objectApiName;

  handleSuccess(e) {
    // Close the modal window and display a success toast
    this.dispatchEvent(new CloseActionScreenEvent());
    this.dispatchEvent(
      new ShowToastEvent({
        title: "Success",
        message: "Record updated!",
        variant: "success",
      }),
    );
  }
}

在页脚中创建带有按钮的自定义窗体

您可以使用 和 组件在模态主体中创建表单。使用此方法时,请使用组件的页脚槽来包含按钮。lightning-inputlightning-buttonlightning-quick-action-panel

此示例创建一个窗体,用于对联系人记录执行与上一示例类似的快速操作,并在页脚中使用按钮,因为它不使用记录窗体组件。该字段显示使用电线适配器的初始值。getRecord

<lightning-quick-action-panel header="Quick Contact Edit">
  <template lwc:if={contact.data}>
    <lightning-input
      label="First Name"
      value={firstname}
      class="slds-m-bottom_x-small">
    </lightning-input>
    <lightning-input
      label="Last Name"
      value={lastname}
      onchange={handleLastNameChange}
      class="slds-m-bottom_x-small"
      required>
    </lightning-input>
    <lightning-input
      label="Phone"
      type="tel"
      value={phone}
      class="slds-m-bottom_x-small">
    </lightning-input>
  </template>
  <div slot="footer">
    <lightning-button variant="neutral" label="Cancel" onclick={handleCancel}></lightning-button>
    <lightning-button
      variant="brand"
      class="slds-m-left_x-small"
      label="Save"
      type="submit"
      onclick={handleSubmit}
      disabled={disabled}>
    </lightning-button>
  </div>
</lightning-quick-action-panel>

如果“姓氏”字段为空,则“保存”按钮将被禁用。单击“保存”按钮将关闭模式窗口,如果保存成功,则显示 Toast。若要保存记录更改,请调用 updateRecord(recordInput, clientOptions)。

import { LightningElement, api, wire } from "lwc";
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import { updateRecord } from "lightning/uiRecordApi";
import { CloseActionScreenEvent } from "lightning/actions";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import FNAME_FIELD from "@salesforce/schema/Contact.FirstName";
import LNAME_FIELD from "@salesforce/schema/Contact.LastName";
import PHONE_FIELD from "@salesforce/schema/Contact.Phone";

const FIELDS = [FNAME_FIELD, LNAME_FIELD, PHONE_FIELD];

export default class QuickEditExample extends LightningElement {
  disabled = false;
  @api recordId;
  @api objectApiName;

  @wire(getRecord, { recordId: "$recordId", fields: FIELDS })
  contact;

  get firstname() {
    return getFieldValue(this.contact.data, FNAME_FIELD);
  }

  get lastname() {
    return getFieldValue(this.contact.data, LNAME_FIELD);
  }

  get phone() {
    return getFieldValue(this.contact.data, PHONE_FIELD);
  }

  handleCancel(event) {
    // Add your cancel button implementation here
    this.dispatchEvent(new CloseActionScreenEvent());
  }

  handleLastNameChange(event) {
    // Display field-level errors if last name field is empty.
    if (!event.target.value) {
      event.target.reportValidity();
      this.disabled = true;
    } else {
      this.disabled = false;
    }
  }

  handleSubmit(e) {
    // Add your updateRecord implementation

    // Close the modal window and display a success toast
    this.dispatchEvent(new CloseActionScreenEvent());
    this.dispatchEvent(
      new ShowToastEvent({
        title: "Success",
        message: "Record updated!",
        variant: "success",
      }),
    );
  }
}

获取有关主页的信息

您可以使用标准 LWC 功能获取有关当前页面的信息,包括来自导航服务的页面引用、记录 ID 和当前记录的对象 API 名称。

要返回页面引用,请从 lightning/navigation 导入。请参阅导航到页面、记录和列表。CurrentPageReference

若要获取记录 ID 和对象 API 名称,请公开 and 作为属性。请参阅使组件了解其记录上下文和使组件了解其对象上下文。recordIdobjectApiName

此示例显示当前记录的记录 ID 和对象 API 名称。它还返回当前页面引用,该引用描述当前页面及其状态。

<template>
  <p>These two fields are auto-populated based on the record context:</p>
  <p>RecordId: <i>{recordId}</i>, objectApiName: <i>{objectApiName}</i></p>
  <p>{pageRefString}</p>
</template>
import { LightningElement, api, wire } from "lwc";
import { CurrentPageReference } from "lightning/navigation";

export default class RecordContextAction extends LightningElement {
  @api recordId;
  @api objectApiName;

  @wire(CurrentPageReference)
  pageRef;

  get pageRefString() {
    return JSON.stringify(this.pageRef);
  }
}

创建 Headless 快速操作

无头快速操作在 Lightning Web 组件中执行自定义代码。与屏幕操作不同,无头操作不会打开模式窗口。

要使您的组件用作无外设快速操作,请配置目标。请参阅配置组件以执行快速操作。

与记录页面上的其他 Lightning Web 组件不同,LWC 快速操作不会传入 .如果需要访问 ,请在代码中设置 的值。recordIdconnectedCallback()recordIdrecordId

_recordId;
set recordId(recordId) {
    if (recordId !== this._recordId) {
        this._recordId = recordId;

实现 invoke()

在您的 Lightning Web 组件中,始终公开为无头快速操作的公共方法。每次触发快速操作时,都会执行该方法。invoke()invoke()

import { LightningElement, api } from "lwc";

export default class HeadlessSimple extends LightningElement {
  @api invoke() {
    console.log("Hi, I'm an action.");
  }
}

为您的 Lightning Web 组件创建一个空模板。

<template> </template>

若要防止在长时间运行的操作中多次并行执行快速操作,请添加内部布尔标志。

的返回类型为 。返回 a 会使方法异步,但返回的方法将被忽略。invoke()voidPromisePromise

此代码使用布尔标志来阻止双重执行,并使用 a 来等待完成。即使返回类型为 ,代码也会异步执行。Promisesleepvoid

import { LightningElement, api } from "lwc";

export default class HeadlessAsync extends LightningElement {
  isExecuting = false;

  @api async invoke() {
    if (this.isExecuting) {
      return;
    }

    this.isExecuting = true;
    await this.sleep(2000);
    this.isExecuting = false;
  }

  sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}

导航

要导航到 Lightning Experience 中的其他页面、记录或列表,请使用导航服务。

此示例导航到联系人主页。

import { LightningElement, api } from "lwc";
import { NavigationMixin } from "lightning/navigation";

export default class navigateToRecordAction extends NavigationMixin(LightningElement) {
  @api invoke() {
    this[NavigationMixin.Navigate]({
      type: "standard__objectPage",
      attributes: {
        objectApiName: "Contact",
        actionName: "home",
      },
    });
  }
}

请参阅导航到页面、记录和列表。

调度事件

您可以通过快速操作调度自定义事件。此示例使用模块提供的事件按顺序调度两个 Toast。lightning/platformShowToastEvent

import { LightningElement, api } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

export default class DispatchEventAction extends LightningElement {
  @api async invoke() {
    let event = new ShowToastEvent({
      title: "I am a headless action!",
      message: "Hi there! Starting...",
    });
    this.dispatchEvent(event);

    await this.sleep(2000);

    event = new ShowToastEvent({
      title: "I am a headless action!",
      message: "All done!",
    });
    this.dispatchEvent(event);
  }

  sleep(ms) {
    // eslint-disable-next-line @lwc/lwc/no-async-operation
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}

请参阅 Toast 通知和与事件通信。

将电子邮件创建为快速操作

从自定义组件中的按钮启动包含预填充内容的电子邮件编辑器。使用 和 组件创建 QuickAction (Global) Send Email 操作,该操作将打开包含预填充字段值的电子邮件草稿。lightning-navigationlightning-page-reference-utils

在组件的 HTML 文件中,使用 定义导航服务,使用 定义页面引用实用程序,使用 定义操作按钮。lightning-navigationlightning-page-reference-utilslightning-button

在此示例中,该函数在单击时触发,并使用主题和正文文本预填充电子邮件编辑器。handleClick

要在电子邮件编辑器中包含默认文本,请使用该函数。将结果添加到传递到有效负载的页面引用中的属性中。若要使用组件的输入填充电子邮件,请将字段值传递到函数中。encodeDefaultFieldValuesdefaultFieldValuesfieldOverrideencodeDefaultFieldValues

确保您在函数中指定的字段在“发送电子邮件”全局操作的布局中不是只读的。在此示例中,如果“HTML 正文”和“主题”字段为只读,则电子邮件草稿不包含这些字段的预填充文本。encodeDefaultFieldValues

在 HTML 文件中添加一个触发事件处理程序的按钮。

<div>
  <lightning-button
    variant="neutral"
    label="Send an Email"
    onclick={handleClick}>
  </lightning-button>
</div>

然后添加事件处理程序。

import { LightningElement } from "lwc";
import { NavigationMixin } from "lightning/navigation";
import { encodeDefaultFieldValues } from "lightning/pageReferenceUtils";

export default class EmailQuickAction2 extends NavigationMixin(LightningElement) {
  handleClick() {
    var pageRef = {
      type: "standard__quickAction",
      attributes: {
        apiName: "Global.SendEmail",
      },
      state: {
        recordId: "00QB000000BLjUrMAL",
        defaultFieldValues: encodeDefaultFieldValues({
          HtmlBody: "Pre-populated text for the email body.",
          Subject: "Pre-populated Subject of the Email",
        }),
      },
    };

    this[NavigationMixin.Navigate](pageRef);
  }
}

在独立 Aura 应用程序中使用组件

您可以在独立的 Aura 应用程序中使用自定义 Lightning Web 组件。独立应用程序在开发人员控制台中也称为 Lightning 应用程序。

引用 Lightning Web 组件的命名约定是 ,这与在 Aura 组件中使用 Lightning Web 组件的命名约定相同。<namespace:camelCaseComponentName>

这个独立的 Aura 应用程序使用默认命名空间中的 Lightning Web 组件。myComponentc

<!-- sampleApp.app -->
<aura:application>
  <c:myComponent />
</aura:application>