gpt4 book ai didi

javascript - 如何从子组件访问 alpine.js 父组件的属性或方法?

转载 作者:行者123 更新时间:2023-12-03 07:08:08 26 4
gpt4 key购买 nike

这是问题看起来像的一个示例场景,

<div x-data="{ count : 0 }">
<div x-data>
<span x-text="count"></span>
<button x-on:click="count++">Increment</button>
<button x-on:click="count--">Decrement</button>
</div>
</div>

它将能够增加/减少数据 count从子组件。
我想通过使用 $dispatch() 调度自定义事件来处理它。但是在设计方面,我可能需要在父组件和子组件上编写监听器,这使得逻辑更加复杂,因为它也应该是响应式(Reactive)的。
有一个 Github issue ,并且提出的解决方案都没有奏效。

最佳答案

I thought of handling it through dispatching custom events using $dispatch() but then again in terms of design, I might need to write listeners on both parent and child component which make the logic more complex since it should be reactive as well.


这是问题的症结所在,为了进行父子和子父通信,您需要使用事件。在子 -> 父的情况下,您将触发 incrementdecrement事件(将在父组件中使用 x-on:incrementx-on:decrement 进行监听)。在父 -> 子的情况下,您需要使用 $watch随时触发更新 count更新(我将使用 new-count 事件名称),这将在 window 上收听从子组件使用 x-on:new-count.window .
这是完整的工作解决方案(将其视为 CodePen ):
<div
x-data="{ count : 0 }"
x-init="$watch('count', val => $dispatch('new-count', val))"
x-on:increment="count++"
x-on:decrement="count--"
>
<div>In root component: <span x-text="count"></span></div>
<div
x-data="{ count: 0 }"
x-on:new-count.window="count = $event.detail"
>
<div>In nested component <span x-text="count"></span></div>
<button x-on:click="$dispatch('increment')">Increment</button>
<button x-on:click="$dispatch('decrement')">Decrement</button>
</div>
</div>
在您提出的情况下, count使用与 Alpine.js 集成的全局存储(例如 Spruce)可能会更好地服务于 state。 ,在这种情况下,我们将读取并更新父组件和子组件都订阅的共享全局存储(请参阅 Spruce 文档)。您可以在以下 CodePen 中找到工作示例.
<div x-data x-subscribe="count">
<div>In root component: <span x-text="$store.count"></span></div>
<div x-data x-subscribe="count">
<div>In nested component <span x-text="$store.count"></span></div>
<button x-on:click="$store.count ++">Increment</button>
<button x-on:click="$store.count--">Decrement</button>
</div>
</div>
<script>
Spruce.store('count', 0);
</script>
应该提到的最终解决方案是删除嵌套组件将意味着计数增量和减量将按预期工作。显然,这个例子可能是简化的并且是为了说明,所以这个解决方案在很多情况下可能不起作用。注意:唯一的区别是删除第二个 x-data .
<div x-data="{ count : 0 }">
<div>
<span x-text="count"></span>
<button x-on:click="count++">Increment</button>
<button x-on:click="count--">Decrement</button>
</div>
</div>

关于javascript - 如何从子组件访问 alpine.js 父组件的属性或方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62612231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com