[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

相关文章

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca

POJ 1018 Communication System(枚举)

题目: http://poj.org/problem?id=1018 题解: 我们可以枚举每一种B可能的值,然后寻找每一行里大于等于B里最小的P。 代码: #include<cstdio>#include<stdlib.h>struct in{double B,P;}a[101][101];double b[10001];int t[101];int cmp(cons

Lenze伦茨EMF2102IBC−LECOM−A/B/LI L−force Communication手测

Lenze伦茨EMF2102IBC−LECOM−A/B/LI L−force Communication手测

Journal of Visual Communication and Image Representation (JVCI)投稿经验分享

网站:Journal of Visual Communication and Image Representation | ScienceDirect.com by Elsevier 影响因子:2.678 CiteScore:4.9 SCI:三区          今年3月份,开始向 Journal of Visual Communication and Image Representa

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

连接MySQL提示: ERROR 2013 (HY000): Lost connection to MySQL server at ‘reading initial communication packet’, system error: 0 这是由于库文件初始化连接MySQL时连接失败引起的。 导致此错误的原因有: 1.服务器为正常启动的; 2.mysql设置文件中“bind-address”

ISO 26262中的失效率计算:SN 29500-4 Expected values for passive components

目录 概要 1 基准条件下的失效率 2 失效率转换 2.1 失效率预测模型 2.2 电压应力系数 2.2.1 电压应力系数计算模型 2.2.2 电压应力系数计算 2.3 温度应力系数 2.3.1 温度应力系数计算模型 2.3.2 温度应力系数计算 2.4 质量系数 3 任务剖面应力系数 4 早期失效系数 概要 SN 29500 是西门子(Siemens)制定的

【C#】【EXCEL】Bumblebee/Components/Analysis/GH_Ex_Ana_CondAverage.cs

Bumblebee/Components/Analysis/GH_Ex_Ana_CondAverage.cs 这段代码定义了一个名为 GH_Ex_Ana_CondAverage 的类,它是一个 Grasshopper 组件。这个组件的主要功能是为 Excel 工作表中的一个范围添加基于平均值的’条件格式’。以下是对这个组件的功能和特点的详细介绍: 组件名称和描述: 名称:Conditiona

【C#】【EXCEL】Bumblebee/Components/Analysis/GH_Ex_Ana_CondBetween.cs

这段代码定义了一个名为 GH_Ex_Ana_CondBetween 的 Grasshopper 组件,其主要功能是为 Excel 工作表中的特定范围添加条件格式。具体来说: 功能概述: 为 Excel 中的数据范围添加基于区间值的条件格式允许用户自定义高亮颜色提供选项来反转条件(高亮区间外的值)可以清除现有的条件格式可以控制是否激活条件格式 输入参数: 工作表数据范围数据区间(用于评估的数值

UE基础 —— Components

目录 Component Instancing Instanced Static Mesh Component Instanced Static Mesh Differences of an ISM and a Static Mesh Component Hierarchical Instanced Static Mesh Instancing Systems Working wit

Vue3+Vite 解决“找不到模块“@/components/xxx.vue”或其相应的类型声明 ts(2307)”

1. 安装插件 pnpm i @types/node -D 2. 修改vite.config.ts文件 import path from 'path';resolve: {alias: {"@": path.resolve(__dirname,"./src"),},}, 3. 修改tsconfig.app.json文件 别人教的都是修改tsconfig.json文件,但是我发现可