了解环信:
http://docs-im.easemob.com/im/web/intro/basic#登录
http://docs.easemob.com/start/450errorcode/40weberrorcode
1、vue配置环境:
安装node版本的环信SDK,安装strophe.js

cnpm install easemob-websdk --save
cnpm install strophe.js

2、找到node_modules/easemob-websdk/src/connection.js,在里面引入strophe.js 加入config
顶部:

// 这一行的目的是使用Strophe方法
var Strophe = require('../../strophe.js').Strophe;
// 这一行主要是提供$iq、$build、$msg、$pres等方法
var meStrophe = require('../../strophe.js');
// 声明$iq、$build、$msg、$pres等方法
$iq = meStrophe.$iq;
$build = meStrophe.$build;
$msg = meStrophe.$msg;
$pres = meStrophe.$pres;

750行左右

var config = {
    xmppURL: 'im-api.easemob.com',
    apiURL : "http://a1.easemob.com",
    appkey : "",
    // ORGNAME : "",
    // APPLICATIONID : "",
    // CLIENTID : "",
    // ADMIN_TOKEN : "",
    https: false,
    isMultiLoginSessions: true,
    isAutoLogin: true,
    isWindowSDK: false,
    isSandBox: false,
    isDebug: false,
    autoReconnectNumMax: 2,
    autoReconnectInterval: 2,
    isWebRTC: (/Firefox/.test(navigator.userAgent) || /WebKit/.test(navigator.userAgent)) && /^https\:$/.test(window.location.protocol),
    heartBeatWait: 4500,
    isHttpDNS: false,
    msgStatus: true,
    delivery: true,
    read: true,
    saveLocal: false,
    encrypt: {
        type: 'none'
    }
}

3、找到WebIM声明的地方,并加入步骤2声明的配置项
搜索:

 var WebIM = window.WebIM || {}

添加:

WebIM.config = config;

4、找到node_modules/strophe.js/strophe.js,并且加入下面两个方法(大约在2883行左右,我在这个位置添加:在pause方法之后,在resume方法之前)

setJid: function(jid) {
   this.jid = jid;
   this.authzid = Strophe.getBareJidFromJid(this.jid);
this.authcid = Strophe.getNodeFromJid(this.jid);
},
getJid: function() {
return this.jid;
},

main.js

import websdk from 'easemob-websdk'
let webIM = window.WebIM = websdk;
Vue.prototype.$WebIM = webIM;
const imConn = new webIM.connection({
    isMultiLoginSessions: webIM.config.isMultiLoginSessions,
    https: typeof webIM.config.https === 'boolean' ? webIM.config.https : location.protocol === 'https:',
    url: webIM.config.xmppURL,
    isAutoLogin: true,
    heartBeatWait: webIM.config.heartBeatWait,
    autoReconnectNumMax: webIM.config.autoReconnectNumMax,
    autoReconnectInterval: webIM.config.autoReconnectInterval,
    apiUrl: webIM.config.apiURL
})
Vue.prototype.$imConn = imConn

使用页面:
data

sendtext:'',
seedto:'xxxxxxxxxx',
reallyName:''
<h3 class="talk_title">联系对方</h3>
<div class="talk_con">
        <div class="talk_show" id="words">
            <div class="atalk"><span id="asay"><b>{{t.reallyName}}:</b>吃饭了吗?</span></div>
            <div class="btalk"><span id="bsay"><b>您说:</b>:还没呢,你呢?</span></div>
        </div>
        <div class="talk_input">
        <el-input v-model="sendtext" style="height:54px; width:70%; float:left;" type="textarea" placeholder="请输入聊天内容"></el-input> 
        <el-button style="height:54px;width:26%;  float:right;" @click="seed">发送</el-button>
    </div>
</div> 

 <style>
.talk_title{ font-size: 16px; line-height: 40px; font-weight: normal;}
.talk_con {width:100%;height:500px; background:#f9f9f9;}
.talk_show {width:100%;height:420px;border:1px solid #EEEFEE;background:#fff; overflow:auto;}
.talk_input {width:100%;margin:10px auto 0;}
.whotalk {width:80px;height:30px;float:left;outline:none;}
.talk_word {height:26px;padding:0px;float:left;margin-left:10px;outline:none;text-indent:10px;}
.talk_sub {width:56px;height:30px; margin-left:10px;}
.atalk {margin:10px; }
.atalk span {display:inline-block;background:#E6A23C; font-size:12px;border-radius:10px;color:#fff;padding:5px 10px;}
.btalk {margin:10px;text-align:right;  }
.btalk span {display:inline-block;background:#409EFF; font-size:12px;border-radius:10px;color:#fff;padding:5px 10px;}
 </style>

created:

//连接环信
var that = this;
    var user = sessionStorage.getItem('ringLetterName');
    var pwd = sessionStorage.getItem('ringLetterPwd');
    var options = { 
        apiUrl: WebIM.config.apiURL,
        user: user,
        pwd: pwd, 
        appKey: WebIM.config.appkey, 
    };
    this.$imConn.open(options); 
    this.$imConn.listen({
        onOpened: function ( message ) {
            console.log(message)
            if(!message.access_token)
            {sessionStorage.setItem('access_token',message.accessToken);}
            else{sessionStorage.setItem('access_token',message.access_token);}
            this.$imConn.setPresence();
        },
        onError: function ( message ) { 
            //console.log(message);
        }, 
        onTextMessage: function ( message ) {
            var Words = document.getElementById("words"); 
            var str = '<div class="atalk"><span> <b>'+  that.t.reallyName + ':' + '</b>' + message.data +'</span></div>';
            Words.innerHTML = Words.innerHTML + str;
            localStorage.setItem(that.t.billCode,Words.innerHTML)
        }
        
    });

方法

seed(){ 
            var that= this;
            if(that.sendtext == ''){
                 this.$message.error('请填写聊天内容!');
            }
            else{
                this.seedto = that.t.letteName;
                var id =  this.$imConn.getUniqueId();                 // 生成本地消息id
                var msg = new WebIM.message('txt', id);      // 创建文本消息
                msg.set({
                    msg: that.sendtext,                  // 消息内容
                    to: that.seedto,                          // 接收消息对象(用户id)
                    roomType: false,
                    access_token:sessionStorage.getItem('access_token'),
                    ext:{
                        ChatUserId:sessionStorage.getItem('ringLetterName'),
                        memberId:sessionStorage.getItem('ringLetterId'),
                        userName:sessionStorage.getItem('ms_username'),
                        userPic:sessionStorage.getItem('symbol'),
                    }, 
                    success: function (id, serverMsgId) {
                        console.log('成功');
                        var Words = document.getElementById("words");
                        var str = '<div class="btalk"><span><b>您说:</b>' + that.sendtext +'</span></div>';
                        Words.innerHTML = Words.innerHTML + str; 
                        localStorage.setItem(that.t.billCode,Words.innerHTML)
                        this.sendtext = '';
                    },
                    fail: function(e){
                        console.log("Send private text error");
                    }
                });
                // var aa ={
                //     "target_type": "users",
                //     "target": [that.seedto],
                //     "msg": {
                //         "type": "txt",
                //         "msg": that.sendtext
                //     },
                //     "from": "beepay_mfod8u_1525583484715",
                //     "ext": {
                //         "memberId": "671",
                //         "userPic": "http://bp-img.oss-cn-beijing.aliyuncs.com/upload_file/symbol/20180803/102955495020.jpg",
                //         "ChatUserId": "beepay_mfod8u_1525583484715",
                //         "userName": "13717819079"
                //     },
                // success: function (id, serverMsgId) {
                //     var Words = document.getElementById("words");
                //     console.log('成功');
                //     console.log(serverMsgId);
                //     var str = '<div class="btalk"><span>' + that.sendtext +'</span></div>';
                //     Words.innerHTML = Words.innerHTML + str;
                //     this.sendtext = '';
                // },
                // fail: function(e){
                //     console.log("Send private text error");
                // }
                // };
                msg.body.chatType = 'singleChat';
                console.log(msg)
                this.$imConn.send(msg.body);
            }
            
        },
Logo

前往低代码交流专区

更多推荐