Javascript 无法在mounted()内调用函数
我有一个聊天API,正在连接到Vue.js项目 当用户转到聊天室页面时,它会发送一个ajax请求,然后调用获取整个聊天历史记录的函数:Javascript 无法在mounted()内调用函数,javascript,html,vue.js,vuejs2,vue-component,Javascript,Html,Vue.js,Vuejs2,Vue Component,我有一个聊天API,正在连接到Vue.js项目 当用户转到聊天室页面时,它会发送一个ajax请求,然后调用获取整个聊天历史记录的函数: mounted() { $.ajax({ url: `http://localhost:8000/api/rooms/${this.$route.params.id}/`, data: {username: this.username}, type: 'PATCH', success: (data) => { const user
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
})
},
但它在以下方面失败了:
TypeError:\u this.fetchChatSessionHistory不是函数
我知道它可能是在错误的位置定义的,但我不知道如何正确地进行定义。您应该将该函数放在methods属性中,如下所示:
mounted(){
...
},
methods:{
fetchChatSessionHistory (uri){
....
}
}
应将该函数放在methods属性中,如下所示:
mounted(){
...
},
methods:{
fetchChatSessionHistory (uri){
....
}
}
您可以执行以下操作:
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)
}
})
}
您可以执行以下操作:
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)
}
})
}
您的代码结构应该类似于装入的{…},方法:{fetchChatSessionHistory uri{…}您的代码结构应该类似于装入的{…},方法:{fetchChatSessionHistory uri{…}