You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Alpine Store中使用@entangle?遇$wire未定义错误

问题原因

直接在Alpine Store初始化时使用@entangle会触发Cannot read properties of undefined (reading '$wire')错误,因为@entangle生成的响应式代码依赖组件上下文内的$wire对象,但Store是全局初始化的,此时组件的$wire实例还未创建,自然无法找到该对象。

解决方案

不能在Store初始化阶段直接绑定@entangle,需要通过组件上下文关联$wire后再同步数据,以下是两种可行方案:

方案一:在组件x-data中双向同步Store与LiveWire属性

<div x-data="{
    // 先在组件内绑定LiveWire属性
    selectedProjectId: @entangle('selectedProjectId'),
    init() {
        // 初始化同步Store值
        this.$store.currentPage.selectedProjectId = this.selectedProjectId
        
        // 监听组件属性变化,同步到Store
        this.$watch('selectedProjectId', (newVal) => {
            this.$store.currentPage.selectedProjectId = newVal
        })
        
        // 监听Store值变化,同步回LiveWire组件
        this.$store.currentPage.$watch('selectedProjectId', (newVal) => {
            this.selectedProjectId = newVal
        })
    }
}">
<!-- 组件内容 -->
</div>

<script>
document.addEventListener('alpine:init', function () {
    Alpine.store('currentPage', {
        currentState: @js($currentState),
        selectedProjectId: null // 先初始化默认值
    })
})
</script>

方案二:在Store中通过方法接收$wire实例并绑定

<div x-data="{
    init() {
        // 组件初始化时把自身的$wire传给Store
        this.$store.currentPage.setWire(this.$wire)
    }
}">
<!-- 组件内容 -->
</div>

<script>
document.addEventListener('alpine:init', function () {
    Alpine.store('currentPage', {
        currentState: @js($currentState),
        selectedProjectId: null,
        $wire: null,
        
        setWire(wire) {
            this.$wire = wire
            // 同步初始值
            this.selectedProjectId = this.$wire.selectedProjectId
            
            // 监听LiveWire属性更新事件,同步到Store
            this.$wire.on('selectedProjectIdUpdated', (newVal) => {
                this.selectedProjectId = newVal
            })
            
            // 监听Store值变化,同步回LiveWire
            this.$watch('selectedProjectId', (newVal) => {
                if (this.$wire) {
                    this.$wire.set('selectedProjectId', newVal)
                }
            })
        }
    })
})
</script>

内容的提问来源于stack exchange,提问作者Jonathan Ma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:40:44