Laravel echo 无法使用动态 id
Laravel echo not working with dynamically id
我用 pusher ,Laravel echo 和 vue.js 聊天就像图片一样
the chat app
这是 vue.js 代码
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 );
});
}
}
首先,当 current_user_id = 1
仅回显频道 the_chat.1
但是当 current_user_id
更改为 2
时,它仍然只回显到通道 the_chat.1
并且在 console.log
the_chat.2 ----
由于
console.log('the_chat.'+this.current_user_id +' -----');
我觉得这道题比你想象的要难。
首先: 当您安装组件时,此代码运行 window.Echo.channel()
但仅运行一次。当您更改 Id 变量时,此代码将不会再次注册监听频道。
其次:控制台写入修改后的ID变量,因为日志写入器使用那个引用的变量,改变了什么。 (我希望你明白。:) )
解决方法:你应该将ID变量的变化逻辑移到父组件中,并且re-render / re-mount这个组件每次id变化事件。
(或者丑陋的方式:你应该在 id 上创建一个 watch 方法,每当它发生变化时,重新注册频道监听。但是 self re-mountning 不是一个好方法..)
希望对您有所帮助! :)
我用 pusher ,Laravel echo 和 vue.js 聊天就像图片一样
the chat app
这是 vue.js 代码
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 );
});
}
}
首先,当 current_user_id = 1
仅回显频道 the_chat.1
但是当 current_user_id
更改为 2
时,它仍然只回显到通道 the_chat.1
并且在 console.log
the_chat.2 ----
由于
console.log('the_chat.'+this.current_user_id +' -----');
我觉得这道题比你想象的要难。
首先: 当您安装组件时,此代码运行 window.Echo.channel()
但仅运行一次。当您更改 Id 变量时,此代码将不会再次注册监听频道。
其次:控制台写入修改后的ID变量,因为日志写入器使用那个引用的变量,改变了什么。 (我希望你明白。:) )
解决方法:你应该将ID变量的变化逻辑移到父组件中,并且re-render / re-mount这个组件每次id变化事件。 (或者丑陋的方式:你应该在 id 上创建一个 watch 方法,每当它发生变化时,重新注册频道监听。但是 self re-mountning 不是一个好方法..)
希望对您有所帮助! :)