Communicate Across the DOM
The easiest way to communicate between components that aren’t in the same DOM tree is to use Lightning message service (lightning/messageService
). Consider using the publish-subscribe mechanism with the pubsub
module only if you're working in containers that don't support Lightning Message Service. The pubsub
module is no longer officially supported or actively maintained.
To communicate between components in a single Lightning page or across multiple pages, set up a Lightning message channel. The advantage over the publish-subscribe mechanism is that message channels aren’t restricted to a single page. Any component in a Lightning Experience application that listens for events on a message channel updates when it receives a message. It works between Lightning web components, Aura components, and Visualforce pages in any tab or in any pop-out window in Lightning Experience. It also works across namespaces.
To use Lightning Message Service:
- Declare a message channel using the LightningMessageChannel metadata type.
- Publish a message using the publish() function from the @salesforce/messageChannel module.
- Subscribe and unsubscribe to a message using the subscribe() and unsubscribe() functions from the @salesforce/messageChannel module.
In containers that don’t support Lightning Messaging Service, use the pubsub
module. Download the module from github.com/developerforce/pubsub.
In a publish-subscribe pattern, one component publishes an event. Other components subscribe to receive and handle the event. Every component that subscribes to the event receives the event. The pubsub
module restricts events to a single page. You must also manually unregister all components that are registered to pubsub
.
The pubsub
module is not officially supported or actively maintained.
See Also
- Salesforce Developers Blog: Inter-Component Communication Patterns for Lightning Web Components
- Salesforce Developers Blog: Step Up Your LWC Skills