本文介绍了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:
HelloWorld
(父)被创建Test
(子)被创建Test
(child) 被挂载,它发出一个事件HelloWorld
(parent) 被挂载,订阅已经发出的事件
HelloWorld
(parent) is createdTest
(child) is createdTest
(child) is mounted, which emits an eventHelloWorld
(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() 钩子中发出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!