main.js
import GoEasy from "goeasy";
const goEasy = GoEasy.getInstance({
host: "hangzhou.goeasy.io", //若是新加坡区域:singapore.goeasy.io
appkey: "你的commonkey",
modules: ['pubsub']//根据需要,传入‘pubsub’或'im’,或数组方式同时传入
});
Vue.prototype.goEasy = goEasy;
Vue.prototype.pubsub = goEasy.pubsub;
app.vue
export default {
name: 'App',
data() {
return {
messages: [],
content: ""
}
},
beforeMount() {
let self = this;
//连接GoEasy
this.goEasy.connect({
data:{},
onProgress: function(attempts){
self.unshiftMessage("GoEasy is connecting"+ attempts);
},
onSuccess: function(){
self.unshiftMessage("GoEasy connect successfully.");
},
onFailed: function(error){
self.unshiftMessage("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
}
});
//接收消息
this.pubsub.subscribe({
channel: "my_channel",
onMessage: function (message) {
self.unshiftMessage(message.content);
},
onSuccess: function () {
self.unshiftMessage('订阅成功.');
},
onFailed: function (error) {
self.unshiftMessage("订阅失败,错误编码:"+error.code+" 错误信息:"+error.content);
}
});
},
methods: {
sendMessage: function () {//发送消息
let self = this;
if (this.content.trim() !== '') {
//发送消息
this.pubsub.publish({
channel: "my_channel",
message: this.content,
onSuccess: function () {
self.content = "";
console.log("send message success");
},
onFailed: function (error) {
self.unshiftMessage("消息发送失败,错误编码:"+error.code+" 错误信息:"+error.content);
}
});
}
},
unshiftMessage(content) {
let formattedTime = new Date().formatDate("hh:mm");
let message = formattedTime + " " + content;
this.messages.unshift(message);
},
}
}