为什么 Alpine.js 不能处理他们示例中的所有事件?

Why doesn't Alpine.js work with all events from their examples?

我正在尝试 Alpine.js,但某些示例对我不起作用。例如

<button x-on:click="alert('Hello World!')">Say Hi</button>

这不会发出任何警报。

<button x-on:click="console.log('test')">Log</button>

并且这不会将任何内容记录到控制台中。然而其他的东西也有效:

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

这是我的整个页面:

<!DOCTYPE html>
<html>
<body>

<h1>Works</h1>

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

<div x-data="{ open: false }">
    <button @click="open = ! open">Expand</button>

    <div x-show="open">
        Content...
    </div>
</div>

<div x-data="{ title: 'Start Here' }">
    <h1 x-text="title"></h1>
</div>

<button x-data="{ label: 'Click Here' }" x-text="label"></button>


<h1>Doesn't work</h1>

<button x-on:click="console.log('test')">Log</button>

<button x-on:click="alert('Hello World!')">Say Hi</button>

<button @click="$event.target.remove()">Remove Me</button>

<div @foo="console.log('foo was dispatched')">
    <button @click="$dispatch('foo')">Dispatch</button>
</div>


<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
</body>
</html>

我做错了什么?

您不起作用的示例没有 x-data 属性(无论是在它们自己上还是在父级上)。无论是否有数据,x-data 属性都是获取 AlpineJS 功能所必需的。

如果您将整个“不起作用”部分包含在 <div x-data></div> 中,它们应该会起作用:

<div x-data>
    <button x-on:click="console.log('test')">Log</button>

    <button x-on:click="alert('Hello World!')">Say Hi</button>

    <button @click="$event.target.remove()">Remove Me</button>

    <div @foo="console.log('foo was dispatched')">
        <button @click="$dispatch('foo')">Dispatch</button>
    </div>
</div>