[LWC] Components Communication

news2024/7/4 2:20:32

目录

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.coloradmin.cn/o/1467792.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

LeetCode206: 反转链表.

题目描述 给你单链表的头节点 head &#xff0c;请你反转链表&#xff0c;并返回反转后的链表。 示例 解题方法 假设链表为 1→2→3→∅&#xff0c;我们想要把它改成∅←1←2←3。在遍历链表时&#xff0c;将当前节点的 next指针改为指向前一个节点。由于节点没有引用其前一…

websocket了解下

websocket请求长啥样 GET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ Sec-WebSocket-Version: 13 啥是websocket websocket是http的一种&#xff0c;服务器可以主动向客户端推送信息&#xff0c;…

板块一 Servlet编程:第五节 Cookie对象全解 来自【汤米尼克的JAVAEE全套教程专栏】

板块一 Servlet编程&#xff1a;第五节 Cookie对象全解 一、什么是CookieCookie的源码 二、Cookie的具体操作&#xff08;1&#xff09;创建Cookie&#xff08;2&#xff09;获取Cookie&#xff08;3&#xff09;设置Cookie的到期时间&#xff08;4&#xff09;设置Cookie的路径…

lxml库和Xpath提取网页数据的基础与实战:完整指南与实战【第92篇—提取网页】

使用lxml库和Xpath提取网页数据的基础与实战 在网络爬虫和数据抓取中&#xff0c;从网页中提取所需信息是一项常见的任务。lxml库和Xpath是Python中用于解析和提取HTML/XML数据的强大工具。本文将介绍lxml库的基础知识&#xff0c;以及如何使用Xpath表达式来准确地提取网页数据…

Java----认识异常

目录 一、异常的概念与体系结构 1.异常的概念 2.异常的体系结构 3.异常的分类 1. 编译时异常 2. 运行时异常 二、异常的处理 1.认识防御式编程 2.异常的抛出 3.异常的捕获 3.1 异常声明throws throws与throw的区别&#xff1a; 3.2 try-catch捕获并处理 3.3 finally …

unity学习(38)——创建(create)角色脚本(panel)--EventSystem

1.在scripts文件夹下创建一个脚本CreatePlayerPanel.cs&#xff0c;脚本挂到panel上&#xff01;给panel加个tag&#xff0c;叫createPanel&#xff0c;脚本内容如下&#xff1a; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngin…

华为配置WLAN AC和AP之间VPN穿越示例

配置WLAN AC和AP之间VPN穿越示例 组网图形 图1 配置WLAN AC和AP之间VPN穿越示例组网图 业务需求组网需求数据规划配置思路配置注意事项操作步骤配置文件 业务需求 企业用户接入WLAN网络&#xff0c;以满足移动办公的最基本需求。且在覆盖区域内移动发生漫游时&#xff0c;不影响…

redis的搭建 RabbitMq搭建 Elasticsearch 搭建

官网 Download | Redis wget https://github.com/redis/redis/archive/7.2.4.tar.gz 编译安装 yum install gcc g tar -zxvf redis-7.2.4.tar.gz -C /usr/localcd /usr/local/redis make && make install 常见报错 zmalloc.h:50:10: fatal error: jemalloc/jemal…

2024年最值得尝试的创业项目,利用信息差,普通人下班也能做

大家好&#xff0c;我是电商花花。 到了2024年&#xff0c;人们依然在寻找长期可靠的副业项目&#xff0c;但我建议暂时停一下&#xff0c;因为抖音小店这个轻松暴利的副业项目还在等着我们呢。 抖音小店无货源创业项目作为一个轻资产创业项目&#xff0c;操作简单&#xff0…

pi(2)

上一次我们说到了这个程序 #include <iostream> #include <cmath> #include <limits> int continuedFractionTerm(int n) { if (n 0) return 1; if (n % 2 0) { return 2 * n 1; } else { return 2 * n; } } std::pair<int, int> be…

大模型参数高效微调

参数高效微调目的 PEFT技术旨在通过最小化微调参数的数量和计算复杂度&#xff0c;来提高预训练模型在新任务上的性能&#xff0c;从而缓解大型预训练模型的训练成本。这样一来&#xff0c;即使计算资源受限&#xff0c;也可以利用预训练模型的知识来迅速适应新任务&#xff0…

bat脚本检测进程程序的方法

一、脚本检测进程 使用批处理脚本检测程序是否在运行&#xff0c;可以使用tasklist命令来列出当前运行的所有进程&#xff0c;并通过findstr命令来搜索特定的进程名。下面是一个简单的批处理脚本示例&#xff0c;它会检测指定的程序是否在运行&#xff0c;并给出相应的信息&…

python 基础知识点(蓝桥杯python科目个人复习计划49)

今日复习内容&#xff1a;做复习题 例题1&#xff1a;希尔排序 题目描述&#xff1a; 希尔排序是直接插入排序算法的一种更高效的改进版本&#xff0c;但它是非稳定排序算法。希尔排序是基于插入排序的以下两点性质而提出的改进方法之一&#xff1a; 1.插入排序在对几乎已经…

打开 Camera app 出图,前几帧图像偏暗、偏色该怎样去避免?

1、问题背景 使用的安卓平台&#xff0c;客户的应用是要尽可能快的获取到1帧图像效果正常的图片。 但当打开 camera 启动出流后&#xff0c;前3-5帧图像是偏暗、偏色的&#xff0c;如下图所示&#xff0c;是抓取出流的前25帧图像&#xff0c; 前3帧颜色是偏蓝的&#xff0c;…

【前端素材】推荐优质后台管理系统Airmin平台模板(附源码)

一、需求分析 系统定义 后台管理系统是一种用于管理和监控网站、应用程序或系统的在线工具。它通常是通过网页界面进行访问和操作&#xff0c;用于管理网站内容、用户权限、数据分析等。后台管理系统是网站或应用程序的控制中心&#xff0c;管理员可以通过后台系统进行各种管…

中国农业无人机行业市场现状分析与投资前景预测研究报告

全版价格&#xff1a;壹捌零零 报告版本&#xff1a;下单后会更新至最新版本 交货时间&#xff1a;1-2天 第一章农业无人机行业发展综述 第一节农业无人机行业定义及分类 一、农业无人机行业的定义 农业无人机是一种无人驾驶的飞行器来帮助优化农业经营&#xff0c;增加作…

jetson nano——报错(已解决):ModuleNotFoundError: No module named ‘wx‘

目录 1.问题描述&#xff1a;2.报错&#xff0c;如下图&#xff1a;3.**解决&#xff1a;得安装一些wxpython的依赖&#xff0c;然后自己编译**3.1 wxPython链接4.编译过程中的图片&#xff1a;&#xff08;用时48min.....流泪&#xff09;5.编译完成以后的图片6.验证结果7.这是…

怎么在wifi中实现手机和电脑文件互传

有时我们想手机电脑文件互传&#xff0c;数据线却不在身边&#xff0c;这时我们可以用MiXplorer来实现wifi中手机和电脑互相访问文件。 MiXplorer是一款来自著名安卓开发者论坛XDA的作品&#xff0c;免费且功能强大&#xff0c;被很多人誉为是“全能文件管理器”。 1.在手机上…

【JavaEE】_smart tomcat常见问题

目录 1. 插件安装故障问题 2. 端口占用问题 3. 乱码问题 1. 插件安装故障问题 如果由于网络问题在IDEA中无法直接安装插件&#xff0c;可以去IDEA官网进行下载&#xff1a; 进入官网后点击Install安装&#xff0c;得到一个jar包&#xff1a; 把jar包拖拽到idea上即可自动安装…

职业规划,电气工程师的岗位任职资格

电气工程技术人员主要是指精通电气施工技术&#xff0c;从事与电气产相关研发工作并能够解决实际问题&#xff0c;对相关资源进行最终统筹的人员。一般来说&#xff0c;这类人员主要从事绘制、审核和把关电气图纸的工作&#xff0c;在审核电气图纸的时候&#xff0c;会检查施工…