javascript - 在Vue中监听API事件

标签 javascript api vue.js

所以我正在努力寻找一种在vue中监听API事件的方法。尝试使用不同的生命周期 Hook ,例如安装的。

我正在使用这个聊天API:https://www.pubnub.com/docs/chat-engine/chats 并尝试监听其他人发出的消息。

    this.chat.on('message', (payload) => {
        console.log(payload)
    })

但我不知道该把它放在哪里。我使用了安装但它不起作用。他们在这里还有一个 React 示例:https://github.com/pubnub/chat-engine-examples/blob/master/react/src/index.js他们正在使用 componentDidMount。

有谁可以让我监听 API 事件吗?

最佳答案

这对我有用。我已在 pubnub https://www.pubnub.com/docs/chat-engine/getting-started#automagic-pubnub-setup 上自动创建了该应用程序

<template>
  <div id="chat">
    <div v-if="!isLoading">
        <div>
          <form @submit.prevent="sendMessage">
            <input v-model="text"
            type="text"
            placeholder="Say something I am giving up on you" />
        </form>

        <div v-for="(message, index) in messages" :key="index">
          {{message.text}}
        </div>
      </div>
    </div>
    <div v-else>loading...</div>
  </div>
</template>

<script>
import ChatEngineCore from 'chat-engine';

const ChatEngine = ChatEngineCore.create({
  publishKey: 'pub-c-e1fbdcd1-b3a9-4a67-b184',
  subscribeKey: 'sub-c-b023a266-1628-11e8-92ea'
});

const now = new Date().getTime();
const username = ['user', now].join('-');

export default {
  name: 'Chat',
  data() {
    return {
      chat: null,
      me: null,
      isLoading: true,
      text: '',
      messages: []
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      ChatEngine.connect(
        username,
        {
          signedOnTime: now
        },
        'auth-key'
      );

      ChatEngine.on('$.ready', data => {
        this.isLoading = false;
        this.me = data.me;
        this.chat = new ChatEngine.Chat('ChatTest');

        this.chat.on('message', message => {
          this.messages.push(message.data);
        });
      });
    },
    sendMessage() {
      this.chat.emit('message', {
        text: this.text
      });
    }
  }
};
</script>

关于javascript - 在Vue中监听API事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48881991/

相关文章:

javascript - [google-drive-api]如何处理 google API 的 get() alt=media 响应

vue.js - Vue 未定义在独立的 Web 组件中

javascript - 在 Vue 组件中使用 CSS 变量(作用域)

javascript - 太多递归 - jquery - 为什么?

javascript - 计算移动浏览器导航器

php - 剥离文本并用 php 替换 <p> 与/n

vue.js - Vue + Webpack : exclude config. js 被打包工作,但它不加载

javascript - 将十六进制值转换为 unicode 字符

RESTful API : Delete Entity - What should I return as result?

api - 使用 AppEngine Channel API 在多个窗口/选项卡上同步聊天