admin管理员组

文章数量:1279053

I know svelte is great for automatically updating ponents when some of its attributes change. But my scenario is slightly different. To simplify, let's say I have a parent Svelte ponent with two child ponents:

<div>
  <child1 onButtonClicked={handleClick} />
  <child2 (1) />
</div>
<script>
  function handleClick() {
    (2)
  }
</script>

I want that when the user clicks a button inside <child1>, some function executes inside <child2>. What can I put in (1) and (2) to implement this behavior?

All I can think of is having a counter, incrementing it inside handleClick and pass the counter to <child2>, then use $: in <child2> to catch the change. But this would be a very contrived workaround. And of course I could move the code I want to execute from <child2> to the parent ponent, but that is even an uglier workaround, because <child2> is the one that really knows what to do.

I know svelte is great for automatically updating ponents when some of its attributes change. But my scenario is slightly different. To simplify, let's say I have a parent Svelte ponent with two child ponents:

<div>
  <child1 onButtonClicked={handleClick} />
  <child2 (1) />
</div>
<script>
  function handleClick() {
    (2)
  }
</script>

I want that when the user clicks a button inside <child1>, some function executes inside <child2>. What can I put in (1) and (2) to implement this behavior?

All I can think of is having a counter, incrementing it inside handleClick and pass the counter to <child2>, then use $: in <child2> to catch the change. But this would be a very contrived workaround. And of course I could move the code I want to execute from <child2> to the parent ponent, but that is even an uglier workaround, because <child2> is the one that really knows what to do.

Share Improve this question asked Mar 3, 2021 at 13:22 Luis CrespoLuis Crespo 7887 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

Bind the function:

Child2.app

<script>
    .....
    export const someFunc = () => console.log('someFunc');
</script>

....

Your code update:

<script>
  import Child1 ... 
  import Child2 ...

  let child2;
  function handleClick() {
    child2.someFunc();
  }
</script>

<div>
  <Child1 onButtonClicked={handleClick} />
  <Child2 bind:this={child2} />
</div>

or:

<script>
  import Child1 ... 
  import Child2 ...

  let child2;
</script>

<div>
  <Child1 onButtonClicked={child2.someFunc} />
  <Child2 bind:this={child2} />
</div>

Repl: Bind function to call this function from sibling ponent

There are other ways to share a function between ponents. Like sharing a function between the parent and the child ponents using setContext and getContext;

本文标签: javascriptSvelte how to notify a child or sibling componentStack Overflow