[LWC] Components Communication

目录

Overview

​Summary

[Sample Code](#Sample Code)

[1. Parent -> Child - Public Setter / Property / Function](#1. Parent -> Child - Public Setter / Property / Function)

[a. Public Property](#a. Public Property)

[b. Public getters and setters](#b. Public getters and setters)

[c. Public Methods](#c. Public Methods)

[2. Child -> Parent - Custom Event](#2. Child -> Parent - Custom Event)

[3. Unrelated Components - LMS (Lightning Message Service)](#3. Unrelated Components - LMS (Lightning Message Service))

[a. publish message](#a. publish message)

[b. subscribe message](#b. subscribe message)

[Trailhead Project Screenshot](#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)

html 复制代码
<template>
  <lightning-card title="Numerator" icon-name="action:manage_perm_sets">    
    <p class="slds-text-align_center slds-var-m-vertical_medium">
      Count: <lightning-formatted-number value={counter}></lightning-formatted-number>
    </p>
    <!-- controls go here -->
    <c-controls
      class="slds-show slds-is-relative"
      onadd={handleIncrement}
      onsubtract={handleDecrement}
      onmultiply={handleMultiply}>
    </c-controls>
  </lightning-card>
</template>

Parent Level (numerator.js)

javascript 复制代码
import { LightningElement } from "lwc";

export default class Numerator extends LightningElement {
  counter = 0;

  handleIncrement() {
    this.counter++;
  }

  handleDecrement() {
    this.counter--;
  }

  handleMultiply(event) {
    const factor = event.detail;
    this.counter *= factor;
  }
}

Child Level (controls.html)

html 复制代码
<template>
  <lightning-card title="Controls" icon-name="action:upload">
    <lightning-layout>
      <lightning-layout-item flexibility="auto" padding="around-small">
        <lightning-button
          label="Subtract"
          icon-name="utility:dash"
          onclick={handleSubtract}>
        </lightning-button>
      </lightning-layout-item>

      <lightning-layout-item flexibility="auto" padding="around-small">
        <lightning-button
          label="2"
          data-factor="2"
          icon-name="utility:close"
          onclick={handleMultiply}>
        </lightning-button>
        <lightning-button
          label="3"
          data-factor="3"
          icon-name="utility:close"
          onclick={handleMultiply}>
        </lightning-button>
      </lightning-layout-item>

      <lightning-layout-item flexibility="auto" padding="around-small">
        <lightning-button
          label="Add"
          icon-name="utility:add"
          onclick={handleAdd}
          icon-position="right">
        </lightning-button>
      </lightning-layout-item>
    </lightning-layout>
  </lightning-card>
</template>

Child Level (controls.js)

javascript 复制代码
import { LightningElement } from "lwc";

export default class Controls extends LightningElement {
  handleAdd() {
    this.dispatchEvent(new CustomEvent("add"));
  }

  handleSubtract() {
    this.dispatchEvent(new CustomEvent("subtract"));
  }

  handleMultiply(event) {
    const factor = event.target.dataset.factor;
    this.dispatchEvent(
      new CustomEvent("multiply", {
        detail: factor,
      })
    );
  }
}
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.

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
  <masterLabel>CountUpdated</masterLabel>
  <isExposed>true</isExposed>
  <description>Message Channel to pass Count updates</description>
  <lightningMessageFields>
    <fieldName>operator</fieldName>
    <description>This is the operator type of the manipulation</description>
  </lightningMessageFields>
  <lightningMessageFields>
    <fieldName>constant</fieldName>
    <description>This is the number for the manipulation</description>
  </lightningMessageFields>
</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
javascript 复制代码
import { LightningElement, wire } from "lwc";
import { publish, MessageContext } from "lightning/messageService";
import COUNT_UPDATED_CHANNEL from "@salesforce/messageChannel/Count_Updated__c";
export default class RemoteControl extends LightningElement {
  @wire(MessageContext)
  messageContext;
  handleIncrement() {
    // this.counter++;
    const payload = {
      operator: "add",
      constant: 1,
    };
    publish(this.messageContext, COUNT_UPDATED_CHANNEL, payload);
  }
  handleDecrement() {
    // this.counter--;
    const payload = {
      operator: "subtract",
      constant: 1,
    };
    publish(this.messageContext, COUNT_UPDATED_CHANNEL, payload);
  }
  handleMultiply(event) {
    const factor = event.detail;
    // this.counter *= factor;
    const payload = {
      operator: "multiply",
      constant: factor,
    };
    publish(this.messageContext, COUNT_UPDATED_CHANNEL, payload);
  }
}
b. subscribe message
javascript 复制代码
import { LightningElement, wire } from "lwc";
import { subscribe, MessageContext } from "lightning/messageService";
import COUNT_UPDATED_CHANNEL from "@salesforce/messageChannel/Count_Updated__c";
export default class Counts extends LightningElement {
  subscription = null;
  priorCount = 0;
  counter = 0;
  @wire(MessageContext)
  messageContext;
  subscribeToMessageChannel() {
    this.subscription = subscribe(
      this.messageContext,
      COUNT_UPDATED_CHANNEL,
      (message) => this.handleMessage(message)
    );
  }
  handleMessage(message) {
    this.priorCount = this.counter;
    if (message.operator == "add") {
      this.counter += message.constant;
    } else if (message.operator == "subtract") {
      this.counter -= message.constant;
    } else {
      this.counter *= message.constant;
    }
  }
  connectedCallback() {
    this.subscribeToMessageChannel();
  }
}

Trailhead Project Screenshot

Reference

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

相关推荐
小小码虫3 个月前
如何在页面调用utility bar并传递参数至lwc组件
javascript·ecmascript·salesforce·lwc
gqkmiss3 个月前
Chrome 浏览器插件获取网页 window 对象(方案三)
前端·chrome·window·chrome 插件·custom event
zero.zhang7 个月前
salesforce零基础学习(一百三十六)零碎知识点小总结(八)
lightning学习·lwc·salesforce学习·admin学习
zero.zhang9 个月前
salesforce零基础学习(一百三十五)项目中的零碎知识点小总结(七)
lwc·salesforce学习·self learning
zero.zhang9 个月前
Salesforce LWC学习(四十九) RefreshView API实现标准页面更新,自定义组件自动捕捉更新
lightning学习·lwc·salesforce学习
顶呱呱程序1 年前
136基于matlab的自适应滤波算法的通信系统中微弱信号检测程序
python·算法·matlab·信号处理·自适应滤波算法·lms
zero.zhang1 年前
Salesforce LWC学习(四十六) record-picker组件浅谈
lightning学习·lwc·salesforce学习
zero.zhang1 年前
Salesforce LWC学习(四十七) 标准页面更新以后自定义页面如何捕捉?
lightning学习·lwc·salesforce学习
zero.zhang1 年前
Salesforce LWC学习(四十六) 自定义Datatable实现cell onclick功能
lightning学习·lwc·salesforce学习