Good evening.
I am creating a chat application with laravel and vue.js
. I have all the messages listed for my user but now I made conversations selectable so whenever a user selects any of them a particular conversation messages would appear. I console.log'ed the data and whenever I click on the conversation, I can see that I have an array of messages that are needed, but I can't figure out the way how to pass them back to app.js, where messages[]
array is so I could re-render the component to list all the messages for that particular conversation. Some of the code here is not properly validated so just ignore that because for now I am focusing on how to pass back the data.
Thanks!
ChatConversation.vue
export default {
props: ['conversation'],
methods: {
getMessages(conversation_id) {
this.messages = [];
axios.get('/messages/' + conversation_id, conversation_id).then(response => {
console.log(response.data);
// HOW TO SEND THEM BACK???
});
}
}
}
app.js
const app = new Vue({
el: '#app',
data: {
messages: [],
conversations: [],
},
methods: {
addMessage(message) {
this.messages.push(message);
axios.post('/messages', message).then(response => {
});
},
loadMessages(messages) {
this.messages = messages;
}
},
created() {
axios.get('/conversations').then(response => {
this.conversations = response.data;
});
axios.get('/messages').then(response => {
this.messages = response.data;
});
Echo.join('chatroom')
.listen('MessagePosted', (e) => {
this.messages.push({
message: e.message.message,
user: e.user
});
console.log(e);
});
}
});
For this I'd recommend using Vuex or another way of maintaining state. The idea is, you receive data from the api, place it in a vuex store that is available between components, and leverage reactivity to notify the intended recipient that data is available.
When used with a plugin such as this one, your data can persist between browser sessions.
A general work flow would look like this:
Then in
app.js
you would use vuex's helper functions:The messages computed will now be reactive, meaning that you can use it in your template or other computeds and they will update accordingly: