最近公司有項(xiàng)目需要客服聊天功能厚柳,我們選擇了騰訊的IM,對于前端來說很好控制沐兵,前端只需對應(yīng)傳參即可别垮,大多由后端控制。百度了很多都沒找到想要的教程扎谎,所以自己寫下來對于引用IM的實(shí)踐碳想。
功能:
1. 一對一聊天
2.群組聊天
3.默認(rèn)選中對話
4.以及自帶的發(fā)送表情包、文件毁靶、圖片胧奔、消息撤回、多選轉(zhuǎn)發(fā)等類似于QQ的功能
官方demo下載地址:https://github.com/tencentyun/TIMSDK/tree/master/H5
官方SDK文檔:https://web.sdk.qcloud.com/im/doc/zh-cn/SDK.html#login
項(xiàng)目結(jié)構(gòu)見Gitee地址:https://gitee.com/jiangxingjie/tengxun-chat.git
一预吆、下載IM并配置 SDKAppID
和 SECRETKEY
龙填,IM是vue寫的,所以大部分地方可以去自己看明白更改拐叉。
二岩遗、默認(rèn)選中對話,所有的聊天對話都為后端生成凤瘦,前端有一對多的情況宿礁,所以我們通過后端傳值的方式拿到要激活的會(huì)話默認(rèn)選中。默認(rèn)選中調(diào)用vuex里的checkoutConversation方法蔬芥。
注意:一定要isSDKReady梆靖,也就是初始化成功之后再去調(diào)checkoutConversation方法,不然會(huì)因?yàn)槲闯跏蓟瘓?bào)錯(cuò)坝茎。
onReadyStateUpdate({ name }) {
const isSDKReady = name === this.TIM.EVENT.SDK_READY ? true : false;
this.$store.commit("toggleIsSDKReady", isSDKReady);
if (isSDKReady) {
this.tim
.getMyProfile()
.then(({ data }) => {
this.$store.commit("updateCurrentUserProfile", data);
})
.catch((error) => {
this.$store.commit("showMessage", {
type: "error",
message: error.message,
});
});
this.$store.dispatch("getBlacklist");
// 登錄trtc calling
this.trtcCalling.login({
sdkAppID: this.sdkAppID,
userID: this.userID,
userSig: this.userSig,
});
// 默認(rèn)選中要溝通的群
// console.log(this.groupID, '這是默認(rèn)選中要溝通的群')
this.$store.dispatch(
"checkoutConversation",
this.groupID //名片ID
);
}
},
三涤姊、用iframe引入項(xiàng)目
HTML部分
<!-- iframedialog -->
<base-dialog class="dialog-IM" width="1000px" :visible.sync="TimShow" height="800px">
<iframe :src="TimSrc" height="100%" width="100%"></iframe>
</base-dialog>
喚起IMdialog
async toTIM(groupId){
const res = await imMsgClear()
if(res.success){
this.ImMessage = 0
this.TimSrc=process.env.IM_URL+'userId='+this.userInfo.id+'&userSig='+this.userInfo.imSign+'&groupId='+groupId
this.TimShow = true
}
}
因?yàn)橥籭d不能多處登錄IM暇番,所以每次關(guān)掉dialog都要調(diào)用一遍IM的退出api嗤放,我們將IM項(xiàng)目給父頁面?zhèn)髦?br> 在IM項(xiàng)目中調(diào)用vuex里的logout方法,給這個(gè)方法添加上iframe給父頁面?zhèn)髦?/p>
logout(context) {
// 若有當(dāng)前會(huì)話,在退出登錄時(shí)已讀上報(bào)
if (context.rootState.conversation.currentConversation.conversationID) {
tim.setMessageRead({ conversationID: context.rootState.conversation.currentConversation.conversationID })
}
tim.logout().then(() => {
window.parent.postMessage('logout',"*");
context.commit('toggleIsLogin')
context.commit('stopComputeCurrent')
context.commit('reset')
})
}
父頁面接受值
mounted() {
let that = this;
//接受iframe頁面的值
window.addEventListener("message", function (e) {
// console.log(e.data)
if(e.data=='logout'){
that.TimSrc = ''
that.TimShow = false
}
});
}
騰訊IM官方給的是vue項(xiàng)目壁酬,熟悉vue的人改起來應(yīng)該還是挺方便的次酌。
2021-07-12新增router,取參數(shù)更加方便舆乔。