[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-controls
      class="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-button
          label="Subtract"
          icon-name="utility:dash"
          onclick={handleSubtract}>
        </lightning-button>
      </lightning-layout-item>

      <lightning-layout-item flexibility="auto" padding="around-small">
        <lightning-button
          label="2"
          data-factor="2"
          icon-name="utility:close"
          onclick={handleMultiply}>
        </lightning-button>
        <lightning-button
          label="3"
          data-factor="3"
          icon-name="utility:close"
          onclick={handleMultiply}>
        </lightning-button>
      </lightning-layout-item>

      <lightning-layout-item flexibility="auto" padding="around-small">
        <lightning-button
          label="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.mfbz.cn/a/408478.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Vue packages version mismatch 报错解决

问题 npm run dev 运行项目的过程中&#xff0c;报错 Vue packages version mismatch 解决方法 根据报错不难看出是 vue 与 vue-template-compiler 版本产生了冲突&#xff0c;vue 与 vue-template-compiler 的版本是需要匹配的。所以解决的办法就是先修改其中一个的版本将 v…

[C++]宏定义

C/C宏的基本使用方法 宏是C/C所支持的一种语言特性&#xff0c;我对它最初的印象就是它可以替换代码中的符号&#xff0c;最常见的例子便是定义一个圆周率PI&#xff0c;之后在代码中使用 PI 来代替具体圆周率的值。 确实如此&#xff0c;宏提供了一种机制&#xff0c;能够使…

动力学约束下的运动规划算法——两点边界值最优控制问题 OBVP

OBVP 即 optimal bundary value problem&#xff0c;即最优的BVP&#xff0c; BVP 问题其实就是解决 state sampled lattice planning 的基本操作方法。 如果&#xff0c;我们期望无人机从一个状态移动到另一个状态&#xff0c;即给定初始状态和终点状态&#xff0c;求解两个状…

每日五道java面试题之spring篇(五)

目录&#xff1a; 第一题. 使用 Spring 有哪些方式&#xff1f;第二题. 什么是Spring IOC 容器&#xff1f;第三题. 控制反转(IoC)有什么作用?第四题. IOC的优点是什么&#xff1f;第五题. BeanFactory 和 ApplicationContext有什么区别&#xff1f; 第一题. 使用 Spring 有哪…

【Web】CTFSHOW 常用姿势刷题记录(全)

目录 web801 web802 web803 web804 web805 web806 web807 法一&#xff1a;反弹shell 法二&#xff1a;vps外带 web808 web809 web810 web811 web812 web813 web814 web815 web816 web817 web818 web819 web820 web821 web822 web823 web824 web825…

03|Order by与Group by优化

索引顺序依次是 &#xff1a; name,age,position 案例1 EXPLAIN SELECT * FROM employees WHERE name LiLei AND position dev ORDER BY age;分析: 联合索引中只是用到了name字段做等值查询[通过key_len 74可以看出因为name字段的len74]&#xff0c;在这个基础上使用了age进…

Javaweb之SpringBootWeb案例之配置优先级的详细解析

1. 配置优先级 在我们前面的课程当中&#xff0c;我们已经讲解了SpringBoot项目当中支持的三类配置文件&#xff1a; application.properties application.yml application.yaml 在SpringBoot项目当中&#xff0c;我们要想配置一个属性&#xff0c;可以通过这三种方式当中…

什么是MapReduce

1.1 MapReduce到底是什么 Hadoop MapReduce是一个软件框架&#xff0c;基于该框架能够容易地编写应用程序&#xff0c;这些应用程序能够运行在由上千个商用机器组成的大集群上&#xff0c;并以一种可靠的&#xff0c;具有容错能力的方式并行地处理上TB级别的海量数据集。这个定…

docker build基本命令

背景 我们经常会构建属于我们应用自己的镜像&#xff0c;这种情况下编写dockerfile文件不可避免&#xff0c;本文就来看一下常用的dockerfile的指令 常用的dockerfile的指令 首先我们看一下docker build的执行过程 ENV指令&#xff1a; env指令用于设置shell的环境变量&am…

DBAPI如何使用数组类型参数

DBAPI如何使用数组类型参数 需求 根据多个id去查询学生信息 API创建 在基本信息标签&#xff0c;创建参数ids &#xff0c;参数类型选择 Array<bigint> 在执行器标签&#xff0c;填写sql&#xff0c;使用in查询 select * from student where id in <foreach ope…

《Docker 简易速速上手小册》第6章 Docker 网络与安全(2024 最新版)

文章目录 6.1 Docker 网络概念6.1.1 重点基础知识6.1.2 重点案例&#xff1a;基于 Flask 的微服务6.1.3 拓展案例 1&#xff1a;容器间的直接通信6.1.4 拓展案例 2&#xff1a;跨主机容器通信 6.2 配置与管理网络6.2.1 重点基础知识6.2.2 重点案例&#xff1a;配置 Flask 应用的…

设计模式学习笔记 - 面向对象 - 7.为什么要多用组合少用继承?如何决定该用组合还是继承?

前言 在面向对象编程中&#xff0c;有一条非常经典的设计原则&#xff1a;组合优于继承&#xff0c;多用组合少用继承。 为什么不推荐使用继承&#xff1f; 组合比继承有哪些优势&#xff1f; 如何判断该用组合还是继承&#xff1f; 为什么不推荐使用继承&#xff1f; 继承…

企业微信怎么变更企业名称?

企业微信变更主体有什么作用&#xff1f;现在很多公司都用企业微信来加客户&#xff0c;有时候辛辛苦苦积累了很多客户&#xff0c;但是公司却因为各种各样的原因需要注销&#xff0c;那么就需要通过企业微信变更主体的方法&#xff0c;把企业微信绑定的公司更改为最新的。企业…

内核解读之内存管理(8)什么是page cache

文章目录 0. 文件系统的层次结构1.什么是page cache2.感观认识page cache3. Page Cache的优缺点3.1 Page Cache 的优势3.2 Page Cache 的劣势 0. 文件系统的层次结构 在了解page cache之前&#xff0c;我们先看下文件系统的层次结构。 1 VFS 层 VFS &#xff08; Virtual Fi…

Gitflow:一种依据 Git 构建的分支管理工作流程模式

文章目录 前言Gitflow 背景Gitflow 中的分支模型Gitflow 的版本号管理简单模拟 Gitflow 工作流 前言 Gitflow 工作流是一种版本控制流程&#xff0c;主要适用于较大规模的团队。这个流程在团队中进行合作时可以避免冲突&#xff0c;并能快速地完成项目&#xff0c;因此在很多软…

人工智能与机器学习行业新闻:颠覆企业运营方式的 AI 趋势

AI 推动业务转型 人工智能 (AI) 和机器学习已经在重塑各行各业的业务模式。AI 通过处理和整合数据支持战略决策的制定&#xff0c;其规模和速度远远超过了人脑。无疑&#xff0c;未来我们还将在 AI 领域取得许多重大突破&#xff0c;而拥有大量数据的行业可能会从人工智能革命…

Mac OS 下载安装与破解Typora

文章目录 下载Typora破解Typora1. 进入安装目录2. 找到并打开Lincense文件3. 修改激活状态4. 重新打开Typora 下载Typora 官网地址&#xff1a;typora官网 下载最新Mac版&#xff0c;正常安装即可 破解Typora 打开typora,可以看到由于未激活&#xff0c;提示使用期限还剩下15…

Three.js-01快速入门

1.导入three.js库 说明&#xff1a;资源在主页里面能够找到&#xff0c;如果不想使用本地的three.module.js文件&#xff0c;也可以使用在线的文件。 import * as THREE from "../three.module.js"// import * as THREE from https://unpkg.com/three/build/three.m…

学习 LangChain 的 LCEL

学习 LangChain 的 LCEL 0. 引言1. 基本示例&#xff1a;提示模型输出解析器​1-1. Prompt​1-2. Model1-3. Output parser1-4. Entire Pipeline 0. 引言 LCEL(LangChain Expression Language) 可以轻松地从基本组件构建复杂的链&#xff0c;并支持开箱即用的功能&#xff0c;…

mongoose httpserver浅析

文章目录 前言一、结构体及其功能二、函数MG_LOGmg_http_listenmg_mgr_poll question参考链接 前言 mongoose是一款基于C/C的网络库&#xff0c;可以实现TCP, UDP, HTTP, WebSocket, MQTT通讯。mongoose是的嵌入式网络程序更快、健壮&#xff0c;易于实现。 mongoose只有mong…
最新文章