[英]Cannot call a function inside mounted()
I have a chat API that I'm connecting to a Vue.js project.我有一个连接到 Vue.js 项目的聊天 API。
When user goes to a chat room page, it sends an ajax request and then calls the function that fetches the whole chat history:当用户进入聊天室页面时,它会发送一个 ajax 请求,然后调用获取整个聊天记录的函数:
mounted() {
$.ajax({
url: `http://localhost:8000/api/rooms/${this.$route.params.id}/`,
data: {username: this.username},
type: 'PATCH',
success: (data) => {
const user = data.members.find((member) => JSON.parse(member).username === this.username)
if (user) {
// The user belongs/has joined the session
this.fetchChatSessionHistory(this.$route.params.id)
}
}
})
},
fetchChatSessionHistory (uri) {
$.get(`http://127.0.0.1:8000/api/rooms/${uri}/messages/`, (data) => {
this.messages = data.messages
})
},
but it fails with:但它失败了:
TypeError: _this.fetchChatSessionHistory is not a function
类型错误:_this.fetchChatSessionHistory 不是函数
I understand that it might be defined at a wrong place but I have no idea how do it right.我知道它可能被定义在错误的地方,但我不知道如何正确。
You should put that function inside methods
property as follows :您应该将该函数放入
methods
属性中,如下所示:
mounted(){
...
},
methods:{
fetchChatSessionHistory (uri){
....
}
}
You can do the following:您可以执行以下操作:
mounted() {
var _this = this;
$.ajax({
url: `http://localhost:8000/api/rooms/${this.$route.params.id}/`,
data: {username: _this.username},
type: 'PATCH',
success: (data) => {
const user = data.members.find((member) => JSON.parse(member).username === _this.username)
if (user) {
// The user belongs/has joined the session
_this.fetchChatSessionHistory(_this.$route.params.id)
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.