使用Vue.js,是否可以通过单个事件侦听器侦听从众多元素发出的所有事件? [英] With Vue.js, Is it possible to listen to all events emitted from numerous elements with a single event listener?

查看:112
本文介绍了使用Vue.js,是否可以通过单个事件侦听器侦听从众多元素发出的所有事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些div格式化为按钮(总计20 ish).

I have a number of divs formatted to be buttons (20ish in total).

我想要一个单击侦听器(可能在父div上),该侦听器将侦听所有/所有单击,并捕获特定的divsinnerHTML.

I'd like to have a single click listener (possibly on the parent div) that would listen for any/all clicks, and capture that specific divs innerHTML.

除了Vanilla JS或jQuery(我可以听一个id或类)之外,Vue.js是否有办法?

Other than vanilla JS or jQuery–in which I could listen to an id or class–is there a way with Vue.js?

谢谢!

推荐答案

是的,您可以使用事件总线轻松完成此操作:

Yes you can accomplish this easily with an event bus:

var bus = new Vue()

// in component A's method
bus.$emit('my-event', { foo: 'bar' })

// in component B, C, D, etc created hook
bus.$on('my-event', function (data) {
  console.log(data)
})

https://vuejs.org/v2/guide /components.html#Non-Parent-Child-Communication

这篇关于使用Vue.js,是否可以通过单个事件侦听器侦听从众多元素发出的所有事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆