问题
一切正常,但是当我尝试将“ response.data”放入该数组“ this.chat.messages或this.allMessages”并进行记录时,控制台显示“未定义”,但是当我记录整个数据时“ response.data”可以清楚地显示数据。
消息控制器
public function index()
{
return Message::with('user')->get();
}
public function store(Request $request)
{
$user = Auth::user();
$message=auth()->user()->messages()->create(['message'=>$request->message]);
broadcast(new MessageSent($user, $message->load('user')))->toOthers();
return response(['status'=>'Message sent successfully','message'=>$message]);
}
前端代码
<script>
const url = 'http://localhost:8000/messages/';
const app = new Vue({
el: '#app',
data() {
return {
message: null,
chat: {
messages:[]
},
allMessages: []
}
},
methods: {
sendMessage() {
if (!this.message) {
alert('please write something.');
}
axios.post('/messages/', {message: this.message}).then(response => {
this.message=null;
this.chat.messages.push(response.data.message);
console.log("Message Sent");
});
},
fetchMessages() {
axios.get(url).then(response => {
this.chat.messages = response.date;
console.log(this.chat.messages);
console.log("Message Loaded");
}
)
.catch((error) => {
// Error
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
});
}
},
created(){
this.fetchMessages();
}
});
</script>
答案 0 :(得分:0)
由于您的response
不包含名为date
的属性,该属性返回undefined
,因此请更改
this.chat.messages = response.date;
到
this.chat.messages = response.data;
希望有帮助。