我在子组件中有一个方法负责从服务器获取数据,在收到数据后,我试图将数据发送给父组件。下面的方法来自 Vue.component (child)。问题是,父组件无法接收发出的数据。只是为了检查,我将 $emit 代码移到了 axios 请求调用之外,然后它就可以工作了。如果我 $emit 从 axios 内部发出,它就不起作用。
不工作(从 axios 内部发出):
methods:{
methodName: function(){
let self = this;
axios.get('url')
.then(function(response){
if (response.data.res) {
console.log('response is true, i can see this message');
self.$emit('updateparentdata',response.data);
}
});
self.$emit('close');
}
},
工作(从 axios 外部发出):
methods:{
methodName: function(){
let self = this;
self.$emit('updateparentdata','some dummy data');
axios.get('url')
.then(function(response){
if (response.data.res) {
}
});
self.$emit('close');
}
},
这是我的 html 页面中的组件代码,如果从 updateparentdata 发出某些内容,那么它将调用父 vue 中的“updateData”函数。
<modal
v-if="showModal"
@close="showModal = false"
v-on:updateparentdata="updateData">
</modal>
这是我在父vue中的方法,
updateData: function(response){
console.log(response);
},
在我从子组件发出数据后,不会触发此方法。如果我在 axios 外部发出数据,则调用此方法,但如果我从 axios 内部发出数据,则不会调用此方法。
最佳答案
感谢您的回答。
我发现了问题所在,我在 axios 调用之外调用了 $emit('close') 函数。
由于 axios 调用是异步的,在发出请求后,axios 实异常(exception)部的 $emit('close') 实际上关闭了我的模态窗口,从而删除了我的整个组件实例。
这就是为什么 axios 调用中的 $emit('updateparentdata') 函数没有按预期执行的原因。
解决方案一:
我在 axios 请求中移动了 $emit('close') ,所以在收到响应后我关闭了模态窗口。
methods:{
methodName: function(){
let self = this;
axios.get('url')
.then(function(response){
if (response.data.res) {
console.log('response is true, i can see this message');
self.$emit('updateparentdata',response.data);
self.$emit('close');
}
});
}
},
解决方案二:
如@Matija Župančić 所述,我尝试使用 Vue.nextTick 等待更新。这个方法也奏效了。
关于javascript - $emit 没有从 axios 内部向父级发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44189500/