【发布时间】:2020-09-13 09:39:25
【问题描述】:
我正在尝试像这样使用 vue.js 中的调度功能。 但是我收到一个错误,说 this2.$dispatch 不是一个函数......就像你在屏幕截图中看到的那样
message.vue
export default {
data(){
return{
message:'',
isLoading:false,
}
},
methods:{
addMessage(){
if(this.message !=''){
this.sendData();
} else{
this.$fire({
title: "Error",
text: "Enter some text.",
type: "error",
timer: 3000
}).then(r => {
console.log(r.value);
});
setTimeout(() => {
this.isLoading = false
},700)
}
},
sendData(){
this.isLoading = true;
this.$http.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms}).then((response) => {
console.log(response.json());
if(response.body != 'Error'){
this.message = '';
this.$dispatch('new_message', response.json());
} else{
this.isLoading = false;
}
}, (response) =>{
});
}
}
}
然后我试着像这样把它弄出来
chat.vue
export default {
components:{
get_message:getMessage,
add_message:addMessage,
},
data(){
return{
messages:[]
}
},
events:{
'new_message':function(data){
this.messages.push(data);
}
}
}
我在控制台中遇到这个错误...有什么想法可以解决这个问题吗?
【问题讨论】:
-
你能提供更多关于你如何称呼
this.$dispatch('new_message', response.json());的上下文吗? -
最常见的是因为您使用的是
this,但它实际上不是您期望的上下文(例如,您在事件处理程序中使用它,它是元素上下文而不是组件上下文)。除非我们知道您如何使用它,否则我们无法确定这一点 -
@Daniel 我更新了我的代码
-
你试过
this.$store.dispatch('new_message', response.json());吗?我不知道this.$dispatch是做什么的,但我以前没有遇到过。 -
@Daniel 是的,我试过了......现在有一个错误 app.js:1980 Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined
标签: laravel vue.js vuejs2 vue-component vuex