繁体   English   中英

无法在mounted() 内调用函数

[英]Cannot call a function inside mounted()

我有一个连接到 Vue.js 项目的聊天 API。

当用户进入聊天室页面时,它会发送一个 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
    })
  },

但它失败了:

类型错误:_this.fetchChatSessionHistory 不是函数

我知道它可能被定义在错误的地方,但我不知道如何正确。

您应该将该函数放入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)
        }
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM