组件根上的单击事件不起作用

Click event on component root not working

我是 Svelte 的新手,我正在尝试在自定义组件根上放置一个 on:click 事件(在 Vue 中,我通过编写 v-on:click.native= 来解决这个问题...),但似乎我做错了什么,因为事件没有触发。 我在 Svelte repl here 上写了一个简单的例子。单击事件在 'div' 元素上触发,但不在组件上触发。

Svelte 不会自动从组件的根元素代理本机事件,因为 Svelte 组件不需要具有单个根元素(或根本没有任何元素)。

所以你必须自己在组件中连接事件。

您可以完全使用 createEventDispatcher,但还有一个快捷语法可以精确地执行您想要执行的操作,代理本机 DOM 事件。

If the on: directive is used without a value, the component will forward the event, meaning that a consumer of the component can listen for it.

docs

因此,以您的示例为例:

<div on:click>
    <h2>
        {book.title}
    </h2>
    <h5>
        {book.author}
    </h5>
</div>