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

在脚本标记vue2中侦听js代码中的自定义事件

  •  3
  • BT101  · 技术社区  · 8 年前

    我从我的一个曾孙那里发出自定义事件 app.vue 主要部件如下:

    this.$emit('logged');
    

    现在我想在我的 应用程序。vue 主要组件,但我更愿意在 <script> 标记,而不是来自 <template> :

    <template>
        <div>
            <app-header></app-header>
            <router-view></router-view>
            <app-footer></app-footer>
      </div>
    </template>
    
    <script>
        import header from './components/shared/header.vue';
        import footer from './components/shared/footer.vue';
    
        export default {
            components: {
                'app-header': header,
                'app-footer': footer
            }
        }
    
    // can I listen to custom events somewhere here above?
    </script>
    

    这是否可以侦听vue 2中js代码中的自定义事件?我找不到这样的信息。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Decade Moon    8 年前

    阅读 Custom Events Non Parent-Child Communication 在文档中。

    组件发出的事件不会弹出多个级别,因此您将无法直接侦听 logged 曾孙组件从主组件发出的事件,除非在每个级别向上代理该事件。

    或者,您可以使用事件总线进行非父子通信(请参见上面的链接)。

    这是您在代码中侦听事件的方式:

    <template>
      <div>
        <my-component ref="mycomp"></my-component>
      </div>
    </template>
    
    <script>
    
    export default {
      mounted() {
        // You need to have a reference to the component you want to listen to
        // which is why I'm using refs here
        this.$refs.mycomp.$on('logged', () => {
          alert('Got logged event');
        });
      }
    }
    
    </script>
    

    但在上述情况下,你只需要 v-on . 如果您使用的是事件总线,那么您需要使用 $on() $off() 以编程方式。我不会解释事件总线模式,因为我相信它已经被广泛讨论过了。