当前位置: 首页 > news >正文

[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)

<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-controlsclass="slds-show slds-is-relative"onadd={handleIncrement}onsubtract={handleDecrement}onmultiply={handleMultiply}></c-controls></lightning-card>
</template>

Parent Level (numerator.js)

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)

<template><lightning-card title="Controls" icon-name="action:upload"><lightning-layout><lightning-layout-item flexibility="auto" padding="around-small"><lightning-buttonlabel="Subtract"icon-name="utility:dash"onclick={handleSubtract}></lightning-button></lightning-layout-item><lightning-layout-item flexibility="auto" padding="around-small"><lightning-buttonlabel="2"data-factor="2"icon-name="utility:close"onclick={handleMultiply}></lightning-button><lightning-buttonlabel="3"data-factor="3"icon-name="utility:close"onclick={handleMultiply}></lightning-button></lightning-layout-item><lightning-layout-item flexibility="auto" padding="around-small"><lightning-buttonlabel="Add"icon-name="utility:add"onclick={handleAdd}icon-position="right"></lightning-button></lightning-layout-item></lightning-layout></lightning-card>
</template>

Child Level (controls.js)

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 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
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
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

相关文章:

  • 2023 最新 IntelliJ IDEA 2023.3 详细配置步骤演示(图文版)<中文版>
  • 数字签名在游戏里的应用
  • 如何实现多账户管理?海外代理IP推荐
  • 【2024.02.22】定时执行专家 V7.0 发布 - TimingExecutor V7.0 Release - 龙年春节重大更新版本
  • 多维时序 | Matlab实现基于VMD-DBO-GRU、VMD-GRU、GRU的多变量时间序列预测
  • 【PostgreSQL】PostgreSQL详细介绍
  • 怎么才能快速准确地全面地了解一个陌生的行业?
  • matlab经验模式分解的R波检测算法
  • 图像压缩感知的MATLAB实现(OMP)
  • 外包干了3个月,技术倒退1年。。。
  • 操作系统——处理机调度
  • 如何实现一个K8S DevicePlugin?
  • 韩国服务器托管的性能及成本情况
  • Nginx使用
  • 力扣用例题:2的幂
  • 《Javascript数据结构和算法》笔记-「字典和散列表」
  • android 一些 utils
  • AzureCon上微软宣布了哪些容器相关的重磅消息
  • git 常用命令
  • JavaScript学习总结——原型
  • js中的正则表达式入门
  • Markdown 语法简单说明
  • 使用 QuickBI 搭建酷炫可视化分析
  • 视频flv转mp4最快的几种方法(就是不用格式工厂)
  • 双管齐下,VMware的容器新战略
  • 文本多行溢出显示...之最后一行不到行尾的解决
  • 一起参Ember.js讨论、问答社区。
  • 在Docker Swarm上部署Apache Storm:第1部分
  • 终端用户监控:真实用户监控还是模拟监控?
  • !!【OpenCV学习】计算两幅图像的重叠区域
  • #stm32驱动外设模块总结w5500模块
  • $.proxy和$.extend
  • (6)【Python/机器学习/深度学习】Machine-Learning模型与算法应用—使用Adaboost建模及工作环境下的数据分析整理
  • (8)Linux使用C语言读取proc/stat等cpu使用数据
  • (echarts)echarts使用时重新加载数据之前的数据存留在图上的问题
  • (java版)排序算法----【冒泡,选择,插入,希尔,快速排序,归并排序,基数排序】超详细~~
  • (分享)一个图片添加水印的小demo的页面,可自定义样式
  • (附源码)spring boot建达集团公司平台 毕业设计 141538
  • (九)One-Wire总线-DS18B20
  • (九十四)函数和二维数组
  • (一)UDP基本编程步骤
  • (转)ObjectiveC 深浅拷贝学习
  • (转)我也是一只IT小小鸟
  • (轉貼) UML中文FAQ (OO) (UML)
  • .NET Core 成都线下面基会拉开序幕
  • .NET Core跨平台微服务学习资源
  • .NET 使用 ILRepack 合并多个程序集(替代 ILMerge),避免引入额外的依赖
  • .NET 中使用 Mutex 进行跨越进程边界的同步
  • .net连接MySQL的方法
  • .Net下的签名与混淆
  • @data注解_一枚 架构师 也不会用的Lombok注解,相见恨晚
  • []C/C++读取串口接收到的数据程序
  • [20160807][系统设计的三次迭代]
  • [20180224]expdp query 写法问题.txt
  • [AIGC 大数据基础]hive浅谈