With Vue.js, Is it possible to listen to all events emitted from numerous elements with a single event listener?

北战南征 提交于 2019-12-13 19:44:13

问题


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

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.

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

Thanks!


回答1:


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



来源:https://stackoverflow.com/questions/46899901/with-vue-js-is-it-possible-to-listen-to-all-events-emitted-from-numerous-elemen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!