所以我正在努力寻找一种在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/