最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alpine.js how to bind to DOM events with dots in the name - Stack Overflow

programmeradmin1浏览0评论

Using Alpine.js version 2.7.3, a ponent can listen to DOM events using x-on:[event].[modifiers].

But what syntax is used to listen to event names that have dots, like bootstrap's show.bs.modal?

In Vue.js, this can be done by a custom directive (from this question), but I think custom directives can not be created in Alpine.js

Using Alpine.js version 2.7.3, a ponent can listen to DOM events using x-on:[event].[modifiers].

But what syntax is used to listen to event names that have dots, like bootstrap's show.bs.modal?

In Vue.js, this can be done by a custom directive (from this question), but I think custom directives can not be created in Alpine.js

Share Improve this question asked Dec 3, 2020 at 15:39 matheusb.pmatheusb.p 1632 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

You can target event names with dots by using the .dot modifier, which swaps any dashes for dots. For example, if you are going to target show.bs.modal you would do:

<div x-data>
    <div @show-bs-modal.dot="console.log($event)"></div>
</div>

Please see https://alpinejs.dev/directives/on#dot for details.

A round about way is to listen to the custom event name on the document and then re-dispatch the event with a different name that Alpine.js can handle.

document.addEventListener('event.with.dots', function(evt, p1, ...) {
  // params and references to elements will depend on your requirement
  alpineComponentElement.dispatchEvent(new Event('eventwithnodots', {bubbles: true}))
})
<div x-data>
  <div x-on:eventwithnodots="$event"></div>
</div>

It's not possible at the moment since Alpine.js uses dots (.) to denote directive modifiers.

发布评论

评论列表(0)

  1. 暂无评论