当前位置: 首页 > 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

http://www.lryc.cn/news/307616.html

相关文章:

  • Unity中URP实现水体(水下的扭曲)
  • anaconda指定目录创建环境无效/环境无法创建到指定位置
  • 《Docker极简教程》--Docker在生产环境的应用--Docker在生产环境的部署
  • 算法D31 | 贪心算法1 | 455.分发饼干 376. 摆动序列 53. 最大子序和
  • 在IDEA中创建vue hello-world项目
  • 如何获取pnpm存储目录
  • QT两个类之间使用信号槽
  • 【Ubuntu】使用WSL安装Ubuntu
  • 【Node.js】自动生成 API 文档
  • 小红书3C家电行业种草营销策略打法,纯干货
  • 防火墙的内容安全
  • Redis 管道详解
  • 【Redis】理论进阶篇------浅谈Redis的缓存穿透和雪崩原理
  • Rocky Linux安装部署Elasticsearch(ELK日志服务器)
  • Linux浅学笔记04
  • 【Day59】代码随想录之动态规划_647回文子串_516最长回文子序列
  • ECLIP
  • STM32 +合宙1.54“ 电子墨水屏(e-paper)驱动显示示例
  • 使用Postman和JMeter进行signature签名
  • uni-app nvue vue3 setup中实现加载webview,解决nvue中获取不到webview实例的问题
  • IPD(集成产品开发)—核心思想
  • uniapp android 原生插件开发-测试流程
  • MyCAT从入门到实战(配置文件介绍)
  • 【LeetCode-300】最长递增子序列(动归)
  • Mysterious-GIF-攻防世界-MISC
  • 【数据结构和算法初阶(C语言)】链表-单链表(手撕详讲单链表增删查改)
  • 【Go语言】Go语言中的切片
  • Qt程序设计-钟表自定义控件实例
  • Redis的发布订阅功能教程,实现实时消息和key过期事件通知功能
  • 4核8g服务器能支持多少人访问?