Vue js错误推送方法sendMessage

时间:2018-06-04 13:16:39

标签: javascript laravel vue.js

我有方法:

 props: ['convId'],
  data() {
        return {
            messages: [],
            newMessage: ''
        };
 },

 methods: {
        sendMessage() {
            axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
                    .then(response =>  this.messages.push(response.data.data));

            this.messages.push(newMessage);

            this.newMessage = '';

            console.log(this.messages.id); //TypeError: Cannot read property 'id' of undefined
        }
  },

当我尝试更新this.messages。我得到了这个对象的未定义属性。为什么呢?

在请求中我返回对象:

{"body":"test","user_id":1,"type":"text","conversation_id":1,"updated_at":"2018-06-04 13:15:27","created_at":"2018-06-04 13:15:27","id":16,"conversation":{"id":1,"private":1,"data":null,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-04 13:15:27","users":[{"id":1,"name":"Axer","email":"test@gmail.com","created_at":"2018-06-01 12:35:37","updated_at":"2018-06-01 12:35:37","pivot":{"conversation_id":1,"user_id":1,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-01 12:54:33"}},{"id":2,"name":"Testumus","email":"teadasdasd@gmail.com","created_at":"2018-06-01 12:46:30","updated_at":"2018-06-01 12:46:30","pivot":{"conversation_id":1,"user_id":2,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-01 12:54:33"}}]}}

我如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您还没有指定newMessage变量。也许你想插入this.newMessage

如果您尝试获取插入的结果,也许您可​​以将数据库数据返回到响应中然后推送消息,这样您就可以获得id和其他列您正在使用它在控制台上注销。

 axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
       .then((response) {  
             this.messages.push(response.data.data) // Fetched message from server
             this.newMessage = '';
             console.log(this.messages.id); 
  })

答案 1 :(得分:-1)

         props: ['convId'],
          data() {
                return {
                    messages: [],
                    newMessage: ''
                };
         },

         methods: {
                sendMessage() {
                    axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
                            .then((response) {  
                                  this.messages.push(response.data.data);
                                  this.messages.push(newMessage);
                                  this.newMessage = '';
                                  console.log(this.messages.id); 
                             });
                }
          },

试试这个。