VueJS 2 $emit 和 $on

Vin*_*aux 1 vue.js vuejs2

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

我有 2 个组件:Dashboad和DashboardPanel。

在DashboardPanel中,我有一种方法:

execute () {
    // emit to parent
    this.$emit('executeSQL', this.value)
    ...
}
Run Code Online (Sandbox Code Playgroud)

在仪表板中:

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

什么也没发生,我在文档中找不到在哪里使用$on并且我不知道是否可以使用其他方式来实现它?

Nic*_* P. 5

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

<DashboardPanel v-on:executeSQL="doExecuteSQL($event)" />
Run Code Online (Sandbox Code Playgroud)

doExecuteSQL是一种方法Dashboard:

methods: {
  doExecuteSQL(value) { ... }
}
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助。