I use pusher ,Laravel echo and vue.js to make chat just like the picture
the chat app
Here is the vue.js code
var myChat = new Vue({
el: '#myChat',
data: {
the_chat: '',
current_user_id: 1,
},
mounted(){
this.set_user_id();
window.Echo.channel( 'the_chat.'+this.current_user_id )
.listen('SendMessage' ,(e) => {
myChat.the_chat.push(e.chat);
console.log('the_chat.'+this.current_user_id +' -----');
});
},
methods:{
choose_user:function(user_id,model){
$.get(api_get_chat+'/'+user_id,function(response){
myChat.the_chat = response;
myChat.current_user_id = user_id;
console.log( myChat.echo_the_chat_id );
});
}
}
First when the current_user_id = 1
it echoes channel the_chat.1
only
but when current_user_id
changed to 2
, it still echoes to channel the_chat.1
only and in the console.log
the_chat.2 ----
due to
console.log('the_chat.'+this.current_user_id +' -----');
I think the problem is more difficult as you think.
First: When you mount the component, this code runs window.Echo.channel()
but only one time. When you change the Id variable, this code wont register again the channel listening.
Second: The console writes the modified ID variable because the log writer uses that refered variable, what is changed. (I hope you understand. :) )
Solution: you should move the ID variable changing logic to the parent component, and re-render / re-mount this component every id change event. (Or ugly way: you should make a watch method on id, and whenever it changes, reregister the channel listening. But self re-mountning not a good way..)
I Hope it helps! :)