【问题标题】:VueJS how to call API every x seconds (chat)VueJS如何每x秒调用一次API(聊天)
【发布时间】:2019-03-05 14:31:09
【问题描述】:

刚刚学习 Vue,我想建立一个有趣的聊天室。我唯一无法理解的是我应该如何不停地观察“回复”,例如您正在与某人聊天,但每次他键入消息并按 Enter 键时,该消息都会出现在您的屏幕上。

这意味着我必须每 5 秒左右调用一次 API 来检查新消息,对吗?如何做到这一点?在什么生命周期钩子中以及究竟如何?

我希望有人可以向我解释一下如何以最好的方式做到这一点。

附:我正在使用带有 Lumen (Laravel) 的 VueJS。

【问题讨论】:

  • 是时候让你终于熟悉 WebSockets 了!去吧,儿子。

标签: vue.js lumen


【解决方案1】:

如果您使用 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>

【讨论】:

  • 天哪,这太棒了!我需要某种 API 存储,因为我想保存对话,但这太棒了,非常感谢您的回复!
猜你喜欢
  • 1970-01-01
  • 2019-02-01
  • 2012-03-14
  • 1970-01-01
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
相关资源
最近更新 更多