代码之家  ›  专栏  ›  技术社区  ›  JeanValjean

如何在Vue中使用事件总线通过自定义事件传递数据。js 2

  •  3
  • JeanValjean  · 技术社区  · 7 年前

    我正在使用 Vue。js 2.5。十、

    在我的玩具项目中,我实现了一个事件总线(类似于图中所示 here )。 事件总线在Vue prototype中全局注册为 $eventBus

    然后我创建了一个发出事件的组件,如下所示

    this.$eventBus.$emit('actionCompleted')
    

    和另一个注册到该事件以执行其自身功能的( myMethod ),如下所示

    export default {
      created: function () {
          this.$eventBus.$on('actionCompleted', this.myMethod)
      },
      methods: {
        myMethod () {
            console.log('myMethod called')
        }
      }
    }
    

    到目前为止,一切正常。

    问题是:如何将对象传递给自定义事件,以便将其他信息传递给侦听器?

    3 回复  |  直到 7 年前
        1
  •  4
  •   ittus    7 年前

    可以将参数作为第二个参数传递

    this.$eventBus.$emit('actionCompleted', objectParams)

    export default {
      created: function () {
          this.$eventBus.$on('actionCompleted', this.myMethod)
      },
      methods: {
        myMethod (objectParams) {
            console.log('myMethod called', objectParams)
        }
      }
    }
    

    您可以检查 following tutorial

        2
  •  3
  •   Harsh Patel Sam    7 年前

    您可以像这样为单个参数创建事件:

    this.$eventBus.$emit('actionCompleted',args)
    

    可以通过逗号分隔的值传递多个参数。

    多个参数:

    this.$eventBus.$emit('actionCompleted',args1, args2 ...)
    

    传递该参数后,您可以得到如下结果[对于单个参数]:

    export default {
      created: function () {
          this.$eventBus.$on('actionCompleted', this.myMethod)
      },
      methods: {
        myMethod (args) {
            console.log('myMethod called', args)
        }
      }
    }
    
        3
  •  3
  •   Orlandster BigMac    7 年前

    您只需通过事件总线发出对象:

    this.$eventBus.$emit('actionCompleted', this.yourObject)
    

    然后像这样抓住它:

    export default {
      created: function () {
          this.$eventBus.$on('actionCompleted', this.myMethod)
      },
      methods: {
        myMethod (objectParams) {
            console.log('myMethod called', objectParams)
        }
      }
    }