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

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745369095a4624718.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信