【问题标题】:With Vue.js, Is it possible to listen to all events emitted from numerous elements with a single event listener?使用 Vue.js,是否可以使用单个事件侦听器来侦听从众多元素发出的所有事件?
【发布时间】:2018-04-04 14:58:23
【问题描述】:

我有许多 div 被格式化为按钮(总共 20 个)。

我希望有一个单击侦听器(可能在父 div 上),它可以侦听任何/所有点击,并捕获特定的 div innerHTML。

除了 vanilla JS 或 jQuery(我可以在其中收听 id 或类)之外,还有 Vue.js 的方法吗?

谢谢!

【问题讨论】:

标签: events vue.js vuejs2 single-page-application


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 2016-02-10
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2018-09-04
    相关资源
    最近更新 更多