如何从 vanilla js 文件访问 $dispatch 和 Alpinejs 的其他神奇属性?

How to access $dispatch and other magic properties of Alpinejs from vanilla js file?

我正在尝试在 Alpine.js 中构建一个 toast 通知组件。但是我无法从 vanilla js 文件发送通知。

<div
    x-data="
        {
            notices: [],
            visible: [],
            add(notice) {
                notice.id = Date.now()
                this.notices.push(notice)
                this.fire(notice.id)
            },
            fire(id) {
                this.visible.push(this.notices.find(notice => notice.id == id))
                const timeShown = 10000 * this.visible.length
                setTimeout(() => {
                    this.remove(id)
                }, timeShown)
            },
            remove(id) {
                const notice = this.visible.find(notice => notice.id == id)
                const index = this.visible.indexOf(notice)
                this.visible.splice(index, 1)
            },
        }
    "
    class="z-50 p-7 fixed inset-0 w-screen flex flex-col-reverse items-end justify-end pointer-events-none"
    @notice.window="add($event.detail)">
    <template x-for="notice of notices" :key="notice.id">
        <div
            x-show="visible.includes(notice)"
            x-transition:enter="transition ease-in duration-400"
            x-transition:enter-start="transform opacity-0 translate-x-full"
            x-transition:enter-end="transform opacity-100"
            x-transition:leave="transition ease-out duration-500"
            x-transition:leave-start="transform translate-x-0 opacity-100"
            x-transition:leave-end="transform translate-x-full opacity-0"§
            @click="remove(notice.id)"
            class="rounded mb-4 p-3 w-full max-w-md text-green-800 shadow-lg cursor-pointer pointer-events-auto bg-green-200"
            x-text="notice.text">
        </div>
    </template>
</div>

https://codepen.io/nuno360/pen/WNGKmeL

如何从原始 js 文件向此组件发送通知?

您可以使用 element.dispatchEvent(new CustomEvent('notice', { detail: {}, bubbles: true }))

创建自定义事件并发送它(假设您正在选择某种元素)