VueJS 如何每 x 秒调用 API(聊天)
VueJS how to call API every x seconds (chat)
刚刚学习 Vue,我想建立一个有趣的聊天室。我唯一无法理解的是我应该如何不间断地观看 "replies" 例如您正在与某人聊天,但每次他输入消息并按回车键时,该消息都应该出现在您的屏幕上。
这意味着我必须每 5 秒左右进行一次 API 调用,以检查是否有新消息,对吧?一个人会怎么做呢?在什么生命周期钩子中以及究竟如何?
我希望有人能向我解释一下我如何才能以最好的方式做到这一点。
P.S。我正在将 VueJS 与 Lumen (Laravel) 一起使用。
如果您使用的是 websockets,则实际上不需要轮询服务器。当事件到达时,消息将被发送下来。我会推荐像 Vue-Socket.io 这样的插件:https://github.com/MetinSeylan/Vue-Socket.io
这是一篇解释如何使用插件构建聊天应用程序的博客文章:https://www.pubnub.com/tutorials/chatengine/vuejs/chat-app/
基本解决方案如下所示:
<template>
<div class="chat-container">
<div class="heading">
<h1>{{ title + uuid }}</h1>
</div>
<div class="body">
<friend-list></friend-list>
<div class="right-body">
<div class="table">
<chat-log></chat-log>
<message-input></message-input>
</div>
</div>
</div>
</div>
</template>
<script>
import {mapGetters} from 'vuex';
import FriendList from '@/components/FriendList';
import ChatLog from '@/components/ChatLog';
import MessageInput from '@/components/MessageInput';
export default {
name: 'chat-container',
components: {
FriendList,
ChatLog,
MessageInput,
},
data() {
return {
title: 'PubNub ChatEngine and Vue - User: ',
};
},
computed: {
...mapGetters({
uuid: 'getMyUuid',
}),
},
};
<script>
刚刚学习 Vue,我想建立一个有趣的聊天室。我唯一无法理解的是我应该如何不间断地观看 "replies" 例如您正在与某人聊天,但每次他输入消息并按回车键时,该消息都应该出现在您的屏幕上。
这意味着我必须每 5 秒左右进行一次 API 调用,以检查是否有新消息,对吧?一个人会怎么做呢?在什么生命周期钩子中以及究竟如何?
我希望有人能向我解释一下我如何才能以最好的方式做到这一点。
P.S。我正在将 VueJS 与 Lumen (Laravel) 一起使用。
如果您使用的是 websockets,则实际上不需要轮询服务器。当事件到达时,消息将被发送下来。我会推荐像 Vue-Socket.io 这样的插件:https://github.com/MetinSeylan/Vue-Socket.io 这是一篇解释如何使用插件构建聊天应用程序的博客文章:https://www.pubnub.com/tutorials/chatengine/vuejs/chat-app/
基本解决方案如下所示:
<template>
<div class="chat-container">
<div class="heading">
<h1>{{ title + uuid }}</h1>
</div>
<div class="body">
<friend-list></friend-list>
<div class="right-body">
<div class="table">
<chat-log></chat-log>
<message-input></message-input>
</div>
</div>
</div>
</div>
</template>
<script>
import {mapGetters} from 'vuex';
import FriendList from '@/components/FriendList';
import ChatLog from '@/components/ChatLog';
import MessageInput from '@/components/MessageInput';
export default {
name: 'chat-container',
components: {
FriendList,
ChatLog,
MessageInput,
},
data() {
return {
title: 'PubNub ChatEngine and Vue - User: ',
};
},
computed: {
...mapGetters({
uuid: 'getMyUuid',
}),
},
};
<script>