'Which is the best/most idiomatic way to communicate with components in Svelte?

I am trying to understand how to communicate with Svelte components. In my app I have created two components. In one, Antescript.svelte, I communicate with App.svelte using bind; in the other, Postscript.svelte, I communicate using dispatch.

Is one method preferred over the other?

Might I encounter problems using on method rather than the other?

The dispatch method certainly takes more coding, is that a problem?

REPL

App.svelte

<h1>{antescript} {junction} {postscript}</h1>
<div>
    <AnteScript bind:antescript={antescript}/>
</div>
<div>
    <PostScript on:message={postscriptChanged} {postscript}/>
</div>

<script>
import AnteScript from "./AnteScript.svelte";
import PostScript from "./PostScript.svelte";
    
    let antescript = 'start';
    let junction = 'and';
    let postscript = 'finish';
    
    function postscriptChanged(event) {
        postscript = event.detail.text;
    }
</script>

AnteScript.svelte

<input type="text" bind:value={antescript} />

<script>
    export let antescript;
</script>

PostScript.svelte

<input id="postscript" type="text" on:input={textChanged} value={postscript}/>

<script>
    import { createEventDispatcher } from 'svelte';
    const dispatch = createEventDispatcher();
    
    export let postscript;
    
    function textChanged() {
    let postscript_input = document.getElementById("postscript");
    dispatch('message', {
        text: postscript_input.value
    });
    }
</script>


Solution 1:[1]

Svelte proposes multiple ways to communicate between components. It depends mostly on the relationship between the component and how the components should react to change:

  • From a parent component to communicate values to direct children, you can use properties and binding
  • From a child component to its parent, events can be used
  • From a parent component to communicate values to indirect children, you can use a context
  • For a global communication between all components, stores will be used

6 Ways to Do Component Communications in Svelte from betterprogramming.pub

The following article will give you more details: https://betterprogramming.pub/6-ways-to-do-component-communications-in-svelte-b3f2a483913c

The way you've approached it seems totally fine, it's a matter of API. But you could also bind the postscript value, no?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 krampstudio