[Vuejs]-Listening to API events in Vue

3👍

This works for me. I’ve auto created the application on 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>
👤Philip

Leave a comment