如果你看一下广播文献 https://laravel.com/docs/5.6/broadcasting#client-events您将看到两个可以在 Vue.js 应用程序中使用的代码片段。
要广播客户端事件,您可以使用 Echowhisper
method:
Echo.private('chat')
.whisper('typing', {
name: this.user.name
});
要监听客户端事件,您可以使用listenForWhisper
method:
Echo.private('chat')
.listenForWhisper('typing', (e) => {
console.log(e.name);
});
当用户打字时,您可以debounce https://lodash.com/docs#debounce上面的耳语方法。
如果您不想使用像 lodash 这样的其他库,您可以通过简单地包装来实现去抖whisper
在超时的情况下。以下方法将每 300 毫秒广播一次耳语:
isTyping() {
let channel = Echo.private('chat');
setTimeout(function() {
channel.whisper('typing', {
name: this.user.name,
typing: true
});
}, 300);
}
该应用程序需要触发isTyping()
当onkeydown
事件发生在聊天应用程序的输入字段中。
创建应用程序后,您还需要聆听耳语。以下方法将设置typing
收到事件后 600 毫秒内变量为 true。
created() {
let _this = this;
Echo.private('chat')
.listenForWhisper('typing', (e) => {
this.user = e.name;
this.typing = e.typing;
// remove is typing indicator after 0.6s
setTimeout(function() {
_this.typing = false
}, 600);
});
},