无法在mounted() 内调用函数

Des*_*ner 1 html javascript vue.js vue-component vuejs2

我有一个连接到 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
    })
  },
Run Code Online (Sandbox Code Playgroud)

但它失败了:

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

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

Bou*_*him 6

您应该将该函数放入methods属性中,如下所示:

mounted(){
      ...
      },
 methods:{
     fetchChatSessionHistory (uri){
         ....
      }
   }
Run Code Online (Sandbox Code Playgroud)