[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.hqwc.cn/news/492967.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Odoo系统安装部署并结合内网穿透实现固定域名访问本地ERP系统

文章目录 前言1. 下载安装Odoo&#xff1a;2. 实现公网访问Odoo本地系统&#xff1a;3. 固定域名访问Odoo本地系统 前言 Odoo是全球流行的开源企业管理套件&#xff0c;是一个一站式全功能ERP及电商平台。 开源性质&#xff1a;Odoo是一个开源的ERP软件&#xff0c;这意味着企…

mysql的增删改查(常用)

增(insert) 语法&#xff1a; insert into 表名&#xff08;字段&#xff09; values( 字段对应的值) 案例&#xff1a; 创建一个学生表 结构如下&#xff1a; create table student(id int ,name varchar(20),age int); 向表中插入2条数据 create table student(id int ,n…

预测性维修系统的功能分析和建设建议

随着工业领域的不断发展&#xff0c;设备状态监测、健康管理和智能诊断变得愈发重要。预测性维修系统通过先进的技术和可靠性评估&#xff0c;帮助企业判断设备状态&#xff0c;识别故障早期征兆&#xff0c;并生成故障预判&#xff0c;从而提出检维修建议。在这一背景下&#…

c++数据结构算法复习基础--1

一、大体复习内容 复习思路&#xff1b; 二、数据结构算法-常见复杂度汇总介绍-性能对比-图表展示 数据结构: 相互之间存在一种或者多种特定关系的数据元素的集合。在逻辑上可以分为线性结构&#xff0c;散列结构、树形结构&#xff0c;图形结构等等。 数据结构说的是组织…

Linux编程 1.3 系统文件IO- 内核表示

文件IO内核表示 1、内核中的三种数据结构 1.1文件描述符表 文件描述符标志 文件表项指针1.2 文件表项 文件状态标志 读、写、追加、同步和非阻塞等状态标志 当前文件偏移量 i节点表项指针 引用计数器1.3 节点 文件类型和对该文件的操作函数指针 当前文件长度 文件所有者 文…

Python算法题集_全排列

Python算法题集_全排列 题46&#xff1a;全排列1. 示例说明2. 题目解析- 题意分解- 优化思路- 测量工具 3. 代码展开1) 标准求解【标记数组递归】2) 改进版一【指针递归】3) 改进版二【高效迭代模块】4) 改进版三【高效迭代模块极简代码】 4. 最优算法5. 相关资源 本文为Python…

猫头虎分享已解决Bug || 未找到资源:NotFoundError

博主猫头虎的技术世界 &#x1f31f; 欢迎来到猫头虎的博客 — 探索技术的无限可能&#xff01; 专栏链接&#xff1a; &#x1f517; 精选专栏&#xff1a; 《面试题大全》 — 面试准备的宝典&#xff01;《IDEA开发秘籍》 — 提升你的IDEA技能&#xff01;《100天精通鸿蒙》 …

qt debug和release运行都没问题打包之后运行不了

&#x1f482; 个人主页:pp不会算法^ v ^ &#x1f91f; 版权: 本文由【pp不会算法v】原创、在CSDN首发、需要转载请联系博主 &#x1f4ac; 如果文章对你有帮助、欢迎关注、点赞、收藏(一键三连)和订阅专栏哦 问题 qt debug和release运行都没问题打包之后运行不了 原因 环…

编码器转动圈数和单圈脉冲数计算FB(博途SCL代码)

编码器测量相关内容&#xff0c;可以查看专栏相关文章。 1、Smart PLC多圈和单圈脉冲数计算 https://rxxw-control.blog.csdn.net/article/details/131777270https://rxxw-control.blog.csdn.net/article/details/131777270 1、博途PLC 计算FB 待续....

OpenCV开发笔记(七十五):相机标定矫正中使用remap重映射进行畸变矫正

若该文为原创文章&#xff0c;转载请注明原文出处 本文章博客地址&#xff1a;https://blog.csdn.net/qq21497936/article/details/136293833 各位读者&#xff0c;知识无穷而人力有穷&#xff0c;要么改需求&#xff0c;要么找专业人士&#xff0c;要么自己研究 红胖子(红模仿…

2024Node.js零基础教程(小白友好型),nodejs新手到高手,(九)NodeJS入门——http模块

060_http模块_网页URL之绝对路径 hello&#xff0c;大家好&#xff0c;这一个小题的话我们来补充一个之前学习过的内容&#xff0c;就是网页当中的URL&#xff0c;咱们这个小题的话主要是来说一下绝对路径&#xff0c;有同学可能会说&#xff0c;这这这&#xff0c;不对劲&…

【c语言】字符函数和字符串函数(下)

前言 书接上回 【c语言】字符函数和字符串函数(上) 上一篇讲解的strcpy、strcat、strcmp函数的字符串长度是不受限制的 而本篇strncpy、strncat、strcnmp函数的字符串长度是受限制的 欢迎关注个人主页&#xff1a;逸狼 创造不易&#xff0c;可以点点赞吗~ 如有错误&#xff0c;…