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);
            },
        }
    }
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐