Home > Enterprise >  Sending an event and setting a value externally in Svelte?
Sending an event and setting a value externally in Svelte?

Time:01-29

I am trying to both forward an event and let a value be set externally using Svelte. If a button is clicked, the greeting should have from "Hello" to "Goodbye".

App.Svelte

<script>
  import Component from "./Component.svelte";
  const handleMessage = (event, greeting) => {
    if (greeting === "hello") {
      greeting = "goodbye";
    } else {
      greeting = "hello";
    }
  };
</script>

<main>
    <Component on:message={handleMessage}/>
</main>

Component.Svelte

<script>
  import { createEventDispatcher } from "svelte";
  const dispatch = createEventDispatcher();
  export let name = "Friend";
  export let greeting = "hello";

  const func = () => {
    dispatch("message", {});
  };
</script>

<p> {greeting}, {name} </p>
<button on:click={dispatch}> switch greeting</button>

However, whenever I click the button, the desired effect is not achieved. What needs to happen such that clicking a button on the nested component (Component) changes the greeting?

CodePudding user response:

Assuming the component hierarchy is as you describe, I wouldn't use dispatch for this. I would pass a click handler to the child component.

Relevant tutorial doc: https://svelte.dev/tutorial/dom-event-forwarding

App.svelte

<script>
  import Component from "./Component.svelte";
  let greeting = "hello"
    let name = "world"
    const onClick = () => {
      if (greeting === "hello") {
        greeting = "goodbye";
      } else {
        greeting = "hello";
      }
    }
</script>

<main>
    <Component on:click={onClick} {greeting} {name}/>
</main>

Component.svelte

<script>
  export let greeting;
  export let name;
</script>

<p> {greeting}, {name} </p>
<button on:click> switch greeting</button>

If you really wanted to use dispatch:

App.svelte

<script>
  import Component from "./Component.svelte";
  let greeting = "hello"
  let name = "world"
  function handleMessage(e) {
    if (e.detail.name !== "updateGreeting") return;
    if (greeting === "hello") {
      greeting = "goodbye";
    } else {
      greeting = "hello";
    }
  }
</script>

<main>
    <Component on:message={handleMessage} {greeting} {name}/>
</main>

Component.svelte

<script>
    import {createEventDispatcher} from "svelte";
    export let greeting;
    export let name;
    const dispatch = createEventDispatcher();
    const click = () => {
        dispatch("message", {name: "updateGreeting"});
    }
</script>

<p> {greeting}, {name} </p>
<button on:click={click}> switch greeting</button>
  • Related