[LWC] Components Communication

2024-02-24 21:28

本文主要是介绍[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

这篇关于[LWC] Components Communication的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/743418

相关文章

WHAT - NextJS 系列之 Rendering - Server Components

目录 一、Server Components1.1 Server Components特点使用 1.2 Client Components特点使用 1.3 综合使用示例1.4 小结 二、Server Components 优势三、Streaming 特性3.1 基本介绍和使用Streaming的理解工作原理使用示例服务器端组件客户端组件页面流程解释 3.2 HTTP/1.1和HTTP/2中

报错:has naming conflicts with other components, ignored

在 Vue 项目编译时,出现如下报错 [unplugin-vue-components] component "xxx"(xxx/Index.vue) has naming conflicts with other components, ignored.[unplugin-vue-components] component "xxx"(xxx/Index.vue) has naming co

【ISAC】paper_NOMA Empowered Integrated Sensing and Communication

NOMA Empowered Integrated Sensing and Communication. 文章目录 ModelCommunication ModelSensing ModelProblem Formulation Solution Model Dual-functional base station (BS) equipped with an N N N-ant

探索Web Components

title: 探索Web Components date: 2024/6/16 updated: 2024/6/16 author: cmdragon excerpt: 这篇文章介绍了Web Components技术,它允许开发者创建可复用、封装良好的自定义HTML元素,并直接在浏览器中运行,无需依赖外部库。通过组合HTML模板、Shadow DOM、自定义元素和HTML imports

SQLserver --安装程序无法打开注册表项 UNKNOWN\Components\…的解决办法

安装SQL Server时出错: Microsoft SQL Server 2012 Service Pack 1 安装程序 出现以下错误: 无法打开项 UNKNOWN\Components\7A8DE26584BD9F843B3E75C25A993FCB\4B60A24C194BF544F9F7B65170347720。 请验证您是否具有足够的权限访问该项,或者与支持人员联

Java --- serial port communication example codes

/** public SerialBean(int PortID) 本函数构造一个指向特定串口的SerialBean,该串口由参数PortID所指定。PortID = 1 表示COM1,PortID = 2 表示COM2,由此类推。 public int Initialize() 本函数初始化所指定的串口并返回初始化结果。如果初始化成功返回1,否则返回-1。初始化的结果是该串口被Serial

vue中使用路由router-view、components渲染实现命名视图实现经典布局

实现经典布局 有时,您需要同时显示多个视图而不是嵌套它们,例如,创建包含一个sidebar视图和一个main视图的布局。这是命名视图派上用场的地方。您可以在多个视图中命名一个名称,而不是在视图中显示一个名称。router-view不带名称的A将default作为其名称。 一个视图是通过使用组件渲染的,因此,对于同一路线,多个视图需要多个组件。确保使用components(带有s)选项: <!

【FastDev4Android框架开发】AndroidAnnnotations注入框架使用之注入组件Components(九)

转载请标明出处:http://www.jianshu.com/p/ba562173187e 本文出自:【江清清博客-代号独狼】 (一).前言: 前面我们已经对于AndroidAnnotations注入框架的基本介绍项目配置和运行原理做了讲解,今天我们开始具体学习怎么样使用这个框架。 FastDev4Android框架项目地址:https://github.com/jiangqq

unity3d从零开始(三):学习Components

1、简介 在上一节中,我们提到过GameObject包含Components,这一节我们将通过讨论GameObject及最常见的Components(Transform Components)来探讨这种关系。 2、创建一个空对象 打开任意 Unity 场景,创建一个空的GameObject(在 Windows 中使用  Shift-Control-N,或在 Mac 中使用  S

进程通信(IPC-Inter Process Communication)

进程之间的通信通过内核空间实现 IPC技术 ①管道(匿名管道/命名管道-FIFO队列) ②System V IPC(消息队列、信号量和共享内存)  ③套接字(UNIX套接字&Internet套接字) ※信号 软中断,信号提供了一种处理异步事件的方法,作为进程通信的一种机制,由一个进程发送给另一个进程。<signal.h> 信号的产生情况 ①用户在终端按下一个组合键; ②硬件异常; /