跳转至

$nextTick

$nextTick 是一个魔术属性,允许你仅在 Alpine 完成响应式 DOM 更新之后才执行给定的表达式。当你想在 DOM 反映你所做的任何数据更新之后与 DOM 状态交互时,这非常有用。

<div x-data="{ title: 'Hello' }">
    <button
        @click="
            title = 'Hello World!';
            $nextTick(() => { console.log($el.innerText) });
        "
        x-text="title"
    ></button>
</div>

在上面的示例中,控制台将记录 "Hello World!" 而不是 "Hello",因为使用了 $nextTick 来等待 Alpine 完成 DOM 更新。

Promises

$nextTick 返回一个 promise,允许使用 $nextTick 暂停 async 函数,直到待处理的 DOM 更新完成。像这样使用时,$nextTick 也无需传递参数。

<div x-data="{ title: 'Hello' }">
    <button
        @click="
            title = 'Hello World!';
            await $nextTick();
            console.log($el.innerText);
        "
        x-text="title"
    ></button>
</div>