The component communication has become as easy as adding a variable in the script tag as context=module
. There is a need to maintain states with the help of module context instead of states. This means the increment counter from multiple components can use a single function to increment the counter value. Module context makes it possible and increments the counter of the only one component where that function is called. The code given below shows how it's done:
Let's suppose, in a certain condition, a user can select three items from different categories (components), and the cart is incremented by one each time an item is selected regardless of the components to it is added. The user can check carts to check the total number of counts. This synchronized increment is possible with the help of module context.
index.svelte
file<script context="module">let totalCount=0export function totalCount(){return totalCount}</script><script>let count=0function btnHandler(){count += 1totalCount += 1}</script><h2>Cart counter - {count}</h2><button on:click ={btnHandler}>Increment Cart </button><hr />
app.svelte
file<script>import Card, {totalCount} from './index.svelte'</script><div style="text-align:center;margin-top:50px;"><button on:click = {() => alert(totalCount())}>Total items</button><Card /><Card /><Card /></div>
<script context="module"> let totalCount=0 export function allCounts(){ return totalCount } </script> <script> let count=0 function btnHandler(){ count += 1 totalCount += 1 } </script> <h2>Cart counter - {count}</h2> <button on:click ={btnHandler}>Increment Cart </button> <hr />
In index.svelte
:
allCounts
function that is exported to return the total number of increments.btnHandler
that increments counter for the current component as well as the totalCount
variable.In App.svelte
:
Card
and a function allCounts
from index.svelte
to implement module context.allCounts
function imported from index.svelte
.Free Resources