转 VUE项目集成环信WebIM即时通讯以及所遇到的问题
首先:在web端环信是不提供界面的,能拿到的官方的demo也只是用react写的编译后的文件,所以你要自己写UI
其次:使用聊天功能前的登录,是IM用户登录,不是用你的环信账号和密码
最后:这篇文章是以当前最新版sdk写的,当前最新版是
"easemob-websdk": "^1.8.3",
这几天和朋友做的一个web项目中需要集成环信的即时通讯功能,上网查了很多资料,也试做了一个发送消息的demo.感觉用起来真是简单方便,只需要提供Appkey,账号和密码就可以登录环信,而且功能强大,支持发送表情,图片,文件,消息已读,以及视频直播.
做demo的时候只直接使用<script>标签引入的sdk,正如环信所说
集成方式,环信的webSDK集成文档是不包含Vue项目的集成的
我在集成的时候遇到了很多坑
比如找不到Strophe对象 ,再比如使用require方式引入strophe 包Base64未定义,真是头大.后来功夫不负有心人,终于让我变查资料,边摸索,终于解决了所有问题,用户能够上线了.
网上有一篇博文也是介绍环信SDK集成到Vue项目中 地址vue-cli项目集成环信WebIM 另外在环信社区里也有一个文章作为参考Vue-cli整合环信WebIM
下面说一下我的集成方式
npm i easemob-websdk strophe.js --save
安装 easemob-websdk 和strophe.js 包 我用安装后是
"easemob-websdk": "^1.8.3", "strophe.js": "^1.2.16"
修改三个文件/node_modules/strophe.js/strophe.js/node_modules/easemob-websdk/src/connection.js
/webim.config.js
在connection.js中头部加入以下几行代码
var Strophe = require('strophe.js').Strophe;var meStrophe = require('strophe.js');$iq = meStrophe.$iq;$build = meStrophe.$build;$msg = meStrophe.$msg;$pres = meStrophe.$pres;
如图
在strophe.js中
setJid: function (jid) { this.jid = jid; this.authzid = Strophe.getBareJidFromJid(this.jid); this.authcid = Strophe.getNodeFromJid(this.jid); }, getJid: function () { return this.jid; },
如图: 在strophe.js的2896行处添加二个方法,即Strophe.Connection.prototype中
在SDK的配置文件中 webim.config.js中
首行 var WebIM = {}; 替换成
var WebIM = window.WebIM || {}; 尾行添加
window.WebIM = WebIM 3:第三步修改main.js
先引入webim.config.js 再引入sdk为WebIM对象,然后将WebIM对象赋值到Vue的原型上
代码如下
require('./assets/lib/easemob-sdk/webim.config.js')let WebIM = require('easemob-websdk')Vue.prototype.$webim = WebIM const conn = new WebIM.connection({ isMultiLoginSessions: WebIM.config.isMultiLoginSessions, https: typeof WebIM.config.https === 'boolean' ? WebIM.config.https : location.protocol === 'https:', url: WebIM.config.xmppURL, heartBeatWait: WebIM.config.heartBeatWait, autoReconnectNumMax: WebIM.config.autoReconnectNumMax, autoReconnectInterval: WebIM.config.autoReconnectInterval, apiUrl: WebIM.config.apiURL, isAutoLogin: true}) const options = { apiUrl: WebIM.config.apiURL, user: '1', pwd: 'xiuxiutrip123456', appKey: WebIM.config.appkey, success:function (re) { console.log('链接服务器正常') }, error:function (err) { alert(err) }}Vue.prototype.$imconn = connVue.prototype.$imoption = options
第四步:在组件中调用时
代码如下
this.$imoption.user = this.from_usernamethis.$imoption.pwd = this.currentUserpwdthis.$imconn.open(this.$imoption)this.$imconn.listen({ onOpened: function (message) { console.log('用户已上线') }, onClosed: function (message) { console.log('用户已下线') }, onEmojiMessage: this.receiveEmojiMessage, onPictureMessage: this.receivePictureMessage, onTextMessage: this.receiveTextMsg})
到此vue项目集成环信webSDK算是吿一段落了
---------------------
作者:Pmc_Fizz
来源:CSDN
原文:https://blog.csdn.net/github_35631540/article/details/80278114
版权声明:本文为博主原创文章,转载请附上博文链接!