VueJS 2 无法在mounted()、created() 钩子中发出事件 [英] VueJS 2 can't emit event in mounted(), created() hooks

查看:25
本文介绍了VueJS 2 无法在mounted()、created() 钩子中发出事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出乎意料,发射器停止工作:

Out of the blue, emitter stopped working:

事件总线.js

import Vue from 'vue';
export const EventBus = new Vue();

import { EventBus } from '../event-bus';

...

mounted() {
  this.getCart();
}

...

methods: {
      getCart() {
        axios.get(`${app.api_erp_url}/cart/${this.cartId}`).then((response) => {
          this.cart = response.data;
          EventBus.$emit('cartLoaded', this.cart); // this not working
        });
      }
},

another-component.vue

another-component.vue

mounted() {
      // MiniCart.vue
      EventBus.$on('cartLoaded', (payload) => {
        ...
      });
    },

无论我如何尝试在 mounted/created 中发出事件,它都不起作用.在点击或其他方面触发事件时没有问题.

No matter how I try to emit the event inside mounted/created, it will not work. No problems when firing events on click or something.

创建沙盒:https://Codesandbox.io/s/gracious-kilby-m43ih?fontsize=14&hidenavigation=1&theme=dark

推荐答案

子组件挂载之前 他们的父组件.

Child components mount before their parent component.

这是您的示例中出现的序列:

This is the sequence occurring in your example:

  1. HelloWorld(父)被创建
  2. Test(子)被创建
  3. Test (child) 被挂载,它发出一个事件
  4. HelloWorld (parent) 被挂载,订阅已经发出的事件
  1. HelloWorld (parent) is created
  2. Test (child) is created
  3. Test (child) is mounted, which emits an event
  4. HelloWorld (parent) is mounted, which subscribes to the event that was already emitted

如果您希望 HelloWorld 从其子级捕获事件,请订阅 created 钩子中的事件.

If you want HelloWorld to catch the event from its children, subscribe to the event in the created hook.

演示

这篇关于VueJS 2 无法在mounted()、created() 钩子中发出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆