VueJS 2 $emit 和 $on

VueJS 2 $emit and $on

我使用 VueJS 2,我真的不知道如何从子组件到父组件进行通信。

我有 2 个组件:DashboadDashboardPanel

DashboardPanel 中,我有一个方法:

execute () {
    // emit to parent
    this.$emit('executeSQL', this.value)
    ...
}

并在 仪表板 中:

mounted () {
   // get event from DashboardPanel
   this.$on('executeSQL', function(value) {
        alert(value)
   })
}

没有任何反应,我在文档中找不到使用 $on 的地方,我不知道是否可以使用其他方法来实现它?

您必须在 Dashboard 组件中指定如何对来自 DashboardPanel 组件的 executeSQL 事件作出反应。在 Dashboard 的 HTML 模板中:

<DashboardPanel v-on:executeSQL="doExecuteSQL($event)" />

doExecuteSQL 正在使用 Dashboard:

的方法
methods: {
  doExecuteSQL(value) { ... }
}

希望这会有所帮助。