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.
1 Answer
Reset to default 13Bind 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
版权声明:本文标题:javascript - Svelte: how to notify a child or sibling component - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741297667a2370910.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论