VueJS如何每x秒调用一次API(聊天)

问题描述 投票:1回答:1

刚刚学习Vue,我想建立一个有趣的聊天。我唯一无法理解的是我应该如何不停地观看“回复”,例如:你正在和某人聊天,但每当他输入一条消息并按下回车时,该消息就会显示在你的屏幕上。

这意味着我必须每5秒左右进行一次API调用,以检查新消息是否正确?怎么会这样呢?在什么生命周期钩子和究竟如何?

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

附:我正在使用VueJS和Lumen(Laravel)。

vue.js lumen
1个回答
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>
© www.soinside.com 2019 - 2024. All rights reserved.