• [LWC] Components Communication


    目录

    Overview

    ​Summary

    Sample Code

    1. Parent -> Child - Public Setter / Property / Function

    a. Public Property

    b. Public getters and setters

    c. Public Methods

    2. Child -> Parent - Custom Event

    3. Unrelated Components - LMS (Lightning Message Service)

    a. publish message

    b. subscribe message

    Trailhead Project Screenshot

    Reference


    Overview

    Summary

    Sample Code

    1. Parent -> Child - Public Setter / Property / Function
    a. Public Property

    b. Public getters and setters

    c. Public Methods

    2. Child -> Parent - Custom Event

    Parent Level (numerator.html)

    1. <template>
    2. <lightning-card title="Numerator" icon-name="action:manage_perm_sets">
    3. <p class="slds-text-align_center slds-var-m-vertical_medium">
    4. Count: <lightning-formatted-number value={counter}>lightning-formatted-number>
    5. p>
    6. <c-controls
    7. class="slds-show slds-is-relative"
    8. onadd={handleIncrement}
    9. onsubtract={handleDecrement}
    10. onmultiply={handleMultiply}>
    11. c-controls>
    12. lightning-card>
    13. template>

    Parent Level (numerator.js)

    1. import { LightningElement } from "lwc";
    2. export default class Numerator extends LightningElement {
    3. counter = 0;
    4. handleIncrement() {
    5. this.counter++;
    6. }
    7. handleDecrement() {
    8. this.counter--;
    9. }
    10. handleMultiply(event) {
    11. const factor = event.detail;
    12. this.counter *= factor;
    13. }
    14. }

    Child Level (controls.html)

    1. <template>
    2. <lightning-card title="Controls" icon-name="action:upload">
    3. <lightning-layout>
    4. <lightning-layout-item flexibility="auto" padding="around-small">
    5. <lightning-button
    6. label="Subtract"
    7. icon-name="utility:dash"
    8. onclick={handleSubtract}>
    9. lightning-button>
    10. lightning-layout-item>
    11. <lightning-layout-item flexibility="auto" padding="around-small">
    12. <lightning-button
    13. label="2"
    14. data-factor="2"
    15. icon-name="utility:close"
    16. onclick={handleMultiply}>
    17. lightning-button>
    18. <lightning-button
    19. label="3"
    20. data-factor="3"
    21. icon-name="utility:close"
    22. onclick={handleMultiply}>
    23. lightning-button>
    24. lightning-layout-item>
    25. <lightning-layout-item flexibility="auto" padding="around-small">
    26. <lightning-button
    27. label="Add"
    28. icon-name="utility:add"
    29. onclick={handleAdd}
    30. icon-position="right">
    31. lightning-button>
    32. lightning-layout-item>
    33. lightning-layout>
    34. lightning-card>
    35. template>

    Child Level (controls.js)

    1. import { LightningElement } from "lwc";
    2. export default class Controls extends LightningElement {
    3. handleAdd() {
    4. this.dispatchEvent(new CustomEvent("add"));
    5. }
    6. handleSubtract() {
    7. this.dispatchEvent(new CustomEvent("subtract"));
    8. }
    9. handleMultiply(event) {
    10. const factor = event.target.dataset.factor;
    11. this.dispatchEvent(
    12. new CustomEvent("multiply", {
    13. detail: factor,
    14. })
    15. );
    16. }
    17. }
    3. Unrelated Components - LMS (Lightning Message Service)

    Prerequisite:

    Create & Deploy the Message Channel via SFDX CLI - No UI

    1. Create messageChannels folder under "force-app/main/default"
    2. Create "xxx.messageChannel-meta.xml" file (i.e. Count_Updated.messageChannel-meta.xml), sample code FYI.

    1. "1.0" encoding="UTF-8"?>
    2. <LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
    3. <masterLabel>CountUpdatedmasterLabel>
    4. <isExposed>trueisExposed>
    5. <description>Message Channel to pass Count updatesdescription>
    6. <lightningMessageFields>
    7. <fieldName>operatorfieldName>
    8. <description>This is the operator type of the manipulationdescription>
    9. lightningMessageFields>
    10. <lightningMessageFields>
    11. <fieldName>constantfieldName>
    12. <description>This is the number for the manipulationdescription>
    13. lightningMessageFields>
    14. LightningMessageChannel>

    Note: Remember that LMS is an API-based feature, and while it can be managed through the Salesforce CLI or VSCode with the Salesforce Extension Pack, it may not have a direct UI path in all Salesforce editions or orgs. If you're working in an environment where LMS is not fully supported, you may need to rely on the CLI or other development tools for deployment and management.

    a. publish message
    1. import { LightningElement, wire } from "lwc";
    2. import { publish, MessageContext } from "lightning/messageService";
    3. import COUNT_UPDATED_CHANNEL from "@salesforce/messageChannel/Count_Updated__c";
    4. export default class RemoteControl extends LightningElement {
    5. @wire(MessageContext)
    6. messageContext;
    7. handleIncrement() {
    8. // this.counter++;
    9. const payload = {
    10. operator: "add",
    11. constant: 1,
    12. };
    13. publish(this.messageContext, COUNT_UPDATED_CHANNEL, payload);
    14. }
    15. handleDecrement() {
    16. // this.counter--;
    17. const payload = {
    18. operator: "subtract",
    19. constant: 1,
    20. };
    21. publish(this.messageContext, COUNT_UPDATED_CHANNEL, payload);
    22. }
    23. handleMultiply(event) {
    24. const factor = event.detail;
    25. // this.counter *= factor;
    26. const payload = {
    27. operator: "multiply",
    28. constant: factor,
    29. };
    30. publish(this.messageContext, COUNT_UPDATED_CHANNEL, payload);
    31. }
    32. }
    b. subscribe message
    1. import { LightningElement, wire } from "lwc";
    2. import { subscribe, MessageContext } from "lightning/messageService";
    3. import COUNT_UPDATED_CHANNEL from "@salesforce/messageChannel/Count_Updated__c";
    4. export default class Counts extends LightningElement {
    5. subscription = null;
    6. priorCount = 0;
    7. counter = 0;
    8. @wire(MessageContext)
    9. messageContext;
    10. subscribeToMessageChannel() {
    11. this.subscription = subscribe(
    12. this.messageContext,
    13. COUNT_UPDATED_CHANNEL,
    14. (message) => this.handleMessage(message)
    15. );
    16. }
    17. handleMessage(message) {
    18. this.priorCount = this.counter;
    19. if (message.operator == "add") {
    20. this.counter += message.constant;
    21. } else if (message.operator == "subtract") {
    22. this.counter -= message.constant;
    23. } else {
    24. this.counter *= message.constant;
    25. }
    26. }
    27. connectedCallback() {
    28. this.subscribeToMessageChannel();
    29. }
    30. }

    Trailhead Project Screenshot

    Reference

    Communicate Between Lightning Web Components | Salesforce Trailhead
    Inter-Component Communication Patterns for Lightning Web Components | Salesforce Developers Blog

  • 相关阅读:
    pandas DataFrame 数据筛选(2)
    synchronized
    【Unity】加速Unity编辑器模式启动时间
    理论第九课——进制转换(八进制篇)
    Spring中的注解01
    Java项目:ssm酒店管理系统
    Java---Stream进阶
    【CTF_SQL】[极客大挑战 2019]LoveSQL 1
    为什么把k8s比做操作系统:kubernetes与os的架构对比
    【MyBatisⅡ】动态 SQL
  • 原文地址:https://blog.csdn.net/itsme_web/article/details/136274588