在Vue中-如何在其他控件中触发广播以接听事件?

awe*_*awe 1 vuejs2

我有用于步骤的组件,单击下一步按钮时,需要在我的步骤组件中触发事件。

此事件应由其他组件拾取,该组件代表当前步骤中页面的内容。

这是我尝试过的:

步骤组件模板:

<template>
  <div class="steps">
    <div class="steps-content">
      <section class="steps-panel" v-for="(stepPage, index) in steps">
        <header class="posA wrap pTs">{{$t(title)}}</header>
        <component :is="stepPage">
           <!-- Summary component is injected here -->
        </component>
      </section>
    </div>
    <div role="navigation">
      <ol class="fixed nav nav--block steps-nav w100">
        <li class="steps-label txtCap" v-for="(stepPage, index) in steps">
          {{$t(stepPage.name)}}
        </li>
      </ol>
      <button class="steps-button" type="button">
        <i class="pf pf-arrow-left"></i>
        <span class="steps-button-label">{{$tc('previous')}}</span>
      </button>
      <button class="steps-button" type="button" v-on:click="next">
        <span class="steps-button-label">{{$tc('next')}}</span>
        <i class="pf pf-arrow-right"></i>
      </button>
    </div>
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

步骤组成方法:

methods: {
  next(event) {
    console.log('emit stepnext')
    this.$emit('stepnext')
  }
}
Run Code Online (Sandbox Code Playgroud)

v-on:click="next"在步骤模板中(在“下一个”按钮上)使用来调用此命令。从console.log中,我看到click事件已执行,并且$ emit调用不会触发任何错误,因此在这里似乎可以正常工作点。

摘要组件

摘要组件是“步骤”中的组件之一,并由“步骤”模板中的此条目加载:

<component :is="stepPage"></component>
Run Code Online (Sandbox Code Playgroud)

在“摘要”组件中,该组件知道单击该按钮后的操作,我尝试通过在模板中包含此事件来开始处理此事件:

<div class="wrap" v-on:stepnext="stepfinish">
 ... content ...
</div>
Run Code Online (Sandbox Code Playgroud)

...以及摘要组件中名为stepfinish该方法的方法执行该操作,但似乎发出的事件从未到达我的摘要组件。

我该如何解决?

aks*_*aks 6

我认为您正在寻找event bus 以下是官方文档中的摘录:

var bus = new Vue()

// in component A's method
bus.$emit('id-selected', 1)

// in component B's created hook
bus.$on('id-selected', function (id) {
  // ...
})
Run Code Online (Sandbox Code Playgroud)

链接:https//vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

这是同一个博客:https : //alligator.io/vuejs/global-event-bus/


Ham*_*eji 6

使用时的简单解决方案$root

// trigger
this.$root.$emit('my-event');

// listen
this.$root.$on('my-event');
Run Code Online (Sandbox Code Playgroud)