运行 使用 AlpineJS 加载函数

Run function on load with AlpineJS

我有一个按钮,点击它会显示祝酒消息。我试图在显示按钮时自动显示 toast 消息(无需单击它)。

这是我的代码:

<button x-data
    @click="$dispatch('notice', {type: 'success', text: ' Success!'})"
    class="m-4 bg-green-500 text-lg font-bold p-6 py-2 text-white shadow-md rounded">
    Success
</button>

<div
    x-data="noticesHandler()"
    class="fixed inset-0 flex flex-col-reverse items-end justify-start h-screen w-screen"
    @notice.window="add($event.detail)"
    style="pointer-events:none">
    <template x-for="notice of notices" :key="notice.id">
        <div
            x-show="visible.includes(notice)"
            x-transition:enter="transition ease-in duration-200"
            x-transition:enter-start="transform opacity-0 translate-y-2"
            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 mr-6 w-56  h-16 flex items-center justify-center text-white shadow-lg font-bold text-lg cursor-pointer"
            :class="{
                'bg-green-500': notice.type === 'success',
                'bg-blue-500': notice.type === 'info',
                'bg-orange-500': notice.type === 'warning',
                'bg-red-500': notice.type === 'error',
            }"
            style="pointer-events:all"
            x-text="notice.text">
        </div>
    </template>
</div>

<script>
    function noticesHandler() {
        return {
            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 = 2000 * 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)
            },
        }
    }
</script>

尝试使用 x-init 执行此操作,但它不起作用:

<button x-data
        x-init="$dispatch('notice', {type: 'success', text: ' Success!'})"
        class="m-4 bg-green-500 text-lg font-bold p-6 py-2 text-white shadow-md rounded">
        Success
    </button>

关于如何执行此操作的任何想法?

您还需要在此处使用 $nextTick magic,因为 x-initnoticesHandler() 组件准备就绪之前触发。

<button x-data
    x-init="$nextTick(() => {$dispatch('notice', {type: 'success', text: ' Success!'})})"
    class="m-4 bg-green-500 text-lg font-bold p-6 py-2 text-white shadow-md rounded">
    Success
</button>

这样 x-init 等到 Alpine.js 完成 DOM 更新,所以基本上每个组件都准备好了。