laravel - this2.$dispatch 不是函数
问题描述
我正在尝试像这样在 vue.js 中使用调度功能。但是我收到一个错误,说 this2.$dispatch 不是一个函数......就像你在屏幕截图中看到的那样
消息.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) =>{
});
}
}
}
然后我试着像这样把它弄出来
聊天.vue
export default {
components:{
get_message:getMessage,
add_message:addMessage,
},
data(){
return{
messages:[]
}
},
events:{
'new_message':function(data){
this.messages.push(data);
}
}
}
我在控制台中遇到这个错误......有什么想法可以解决这个问题吗?
解决方案
更新
如果您的商店在 Vue 中注册,它似乎应该可以工作。如果您的$dispatch
工作超出了承诺,您可以尝试将this
上下文存储在另一个变量中
sendData(){
this.isLoading = true;
const that = this;
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'){
that.message = '';
that.$dispatch('new_message', response.json());
} else{
that.isLoading = false;
}
}, (response) =>{
});
}
或者只是$dispatch
sendData(){
this.isLoading = true;
const $dispatch = this.$dispatch;
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 = '';
$dispatch('new_message', response.json());
} else{
this.isLoading = false;
}
}, (response) =>{
});
}
在这里猜测一下,但请尝试调用它
this.$store.dispatch('new_message', response.json());
或者,您的问题可能是范围问题(看到这是从承诺中调用的)
如果您在 Promise 处理程序中声明了这样的函数then(function(response){this.$store.dispatch('new_message', response.json());})
,则可能是由于范围
相反,您可以尝试使用箭头功能
then((response) => {
this.$store.dispatch('new_message', response.json());
})
推荐阅读
- javascript - 在不更改条件的情况下根据状态更改重新渲染条件
- javascript - 存储基本身份验证密码的最佳做法是什么?
- sql - Oracle Application Express 在提交文本字段时给出 ORA-06502
- apache - 使用 wsgi 部署时,绘图不从 sqlite db 加载
- python - Python - 无法匹配列表中的值
- ios - 无法推断通用参数“T” Xcode 11 iOS 13
- javascript - 当 body 函数进行条件检查时,应该从 useEffect 钩子返回什么?
- search - 如何使用rest api颤振进行搜索功能
- node.js - 事件发射器Nodejs的单元测试?
- azure-data-factory - Azure datafactory - 触发窗口翻转被阻止