5 Component communication

 

This chapter covers

  • Passing data into components using props
  • Getting data out of components by binding to props
  • Using slots to supply content to be rendered
  • Dispatching events to notify parent elements
  • Using context to pass data to descendant components

Components in non-trivial Svelte applications need to communicate with each other. For example, suppose we have a component that allows a user to enter their mailing address. It can render inputs for street, city, state, and postal code. It also contains logic to verify that the postal code matches the city. Another component that displays a map may want to know when the data in our mailing address component has been changed so it can display the location of the new address.

There are many ways for Svelte components to communicate. Table 5.1 summarizes the available options. It uses the terms “parent,” “child,” “descendant,” and “ancestor” to refer to the relationships between components in the component hierarchy.

Table 5.1 Component communication options (view table figure)

Need

Solution

Parent passes data to child

Props

Parent passes HTML and components to child

Slots

Child notifies parent, optionally including data

Events

Ancestor makes data available to descendants

Context

Component shares data between all instances

Module context

Any component subscribes to data

Stores

5.1 Component communication options

 
 
 
 

5.2 Props

 
 
 
 

5.2.1 Props go in with export

 
 

5.2.2 Reacting to prop changes

 
 

5.2.3 Prop types

 

5.2.4 Directives

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage