【问题标题】:Cannot call a function inside mounted()无法在mounted() 中调用函数
【发布时间】:2019-06-02 10:23:30
【问题描述】:

我有一个正在连接到 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
    })
  },

但它失败了:

TypeError: _this.fetchChatSessionHistory 不是函数

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

【问题讨论】:

  • 你的代码结构应该像mounted(){...},methods:{fetchChatSessionHistory (uri){...}}

标签: javascript html vue.js vuejs2 vue-component


【解决方案1】:

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

mounted(){
      ...
      },
 methods:{
     fetchChatSessionHistory (uri){
         ....
      }
   }

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

    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)
            }
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 2020-07-21
      • 2021-06-08
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2011-08-08
      相关资源
      最近更新 更多