GoEasy基于Vue的连接初始化,替代WebSocket

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值