本次平台开发需要集成融云第三方webIM即时通讯实现单点聊天功能,一开始自己在网上找了写资料,但是不全,后来自己通过查看融云官网,自己手写了一份,分享给大家。(融云官网)。 1、请前往<a href="https://developer.rongcloud/signup">融云官方网站</a>注册开发者帐号,获取appkey(注意生产环境和测试环境的appkey不一样); 2、在vue-cli的index.html中引入相关的js文件;

<!-- 引入融云sdk -->

<script src="https://cdn.ronghub/RongIMLib-2.3.5.min.js"></script>

<!-- 引入融云表情库 -->

<script src="https://cdn.ronghub/RongEmoji-2.2.7.min.js"></script>

3、新建了一个RongImCom.vue 4、按照官方文档,定义方法,如连接状态监听器,消息监听器,连接服务器,获取imToken(这个需要项目开发后台提供接口,返回imToken供前端使用),具体代码如下:

<template>
    <div class="im" v-show="imIsShow">
        <div v-show="alertMsgShow">
            <el-alert
                show-icon
                :title="alertMsg"
                type="warning"
                close-text="重新连接"
                @close="toReconnect">
            </el-alert>
        </div>
        <div class="im-left">
            <ul v-if="conversationList.length>0" class="conversation-list">
                <li
                    v-for="(list, index) in conversationList"
                    :key="list.targetId"
                    @click="selectTarget(list,index)"
                    :class="'list'+list.targetId"
                >
                    <div class="im-border" v-bind:class="targetId ==list.targetId?'active':''">
                        <img
                            :src="getAvartar(list.targetId && list.targetId.slice(2,list.targetId.length))"
                            @error="function(e){defaultAvartar(e)}"
                            alt
                        >
                        <div style="margin:10px 0;display:inline-block;width:119px;overflow:hidden;vertical-align:middle">
                            <p
                                style="font-size:14px;font-weight:600;"
                            >{{list.targetName}}</p>
                        </div>
                    </div>
                </li>
            </ul>
            <p v-if="conversationList.length==0" style="color:white;text-align:center;">暂无会话记录</p>
        </div>
        <span @click="imIsShow = false" class="closeim-btn">
            <i class="el-icon-close"></i>
        </span>
        <div
            style="float:left;width:calc(100% - 217px );border-bottom:1px dashed #ccc;height:440px;box-sizing:border-box;padding:10px;color:#333;overflow-y:auto;"
            class="imMsg-content"
        >
            <p
                style="text-align:center;margin:10px;color:#666;cursor:pointer;"
                @click="getHistoryMsg(false)"
            >{{hasHistoryMsg?'查看更多历史记录':'暂无历史记录'}}</p>

            <div
                v-for="list in conversationList"
                :key="list.targetId"
                :class="list.targetId"
                :show="list.targetId==targetId"
                class="all-say"
            ></div>
        </div>
        <div
            style="float:left;width:calc(100% - 216px );height:160px;box-sizing:border-box;padding:5px 10px;"
        >
            <div style="height:20px;cursor:pointer">
                <div
                    v-show="emojiShow"
                    style="position: absolute; bottom: 158px; background-color: white;"
                >
                    <span style="cursor:pointer"
                        v-for="emList in imEmojiList"
                        :key="emList.unicode"
                        v-html="emList.node.outerHTML"
                        @click="selectEmoji(emList)"
                    ></span>
                </div>

                <div @click="emojiShow = !emojiShow">
                    <img src="../../assets/img/emoji.png" alt class="icon">
                </div>
            </div>
            <div style="height:100px;">
                <textarea
                    cols="80"
                    rows="6"
                    style="border:none;color:#333;"
                    v-model="mySendMsg"
                    v-html="selectEmojiHtml"
                    @keyup.ctrl.enter="sendMsg"
                >
                    <span></span>
                </textarea>
            </div>
            <el-button size="mini" type="primary" style="float:right" @click="sendMsg">发送 Ctrl+Enter</el-button>
        </div>
    </div>
</template>
<script>
import bus from "@/components/common/bus.js";
export default {
    data: function() {
        return {
            loaded: false,
            imIsShow: false, // im弹框是否显示
            alertMsgShow: false,//警告提示是否显示
            alertMsg:'',
            conversationList: [],
            mySendMsg: "",
            emojiShow: false, //是否显示表情
            appkey:  '',
            config: {
                size: 24, // 大小, 默认 24, 建议18 - 58
                url: "//f2e.ronghub/sdk/emoji-48.png", // Emoji 背景图片
                lang: "zh", // Emoji 对应名称语言, 默认 zh
                // 扩展表情
                extension: {
                    dataSource: {
                        u1F914: {
                            en: "thinking face", // 英文名称
                            zh: "思考", // 中文名称
                            tag: "?", // 原生 Emoji
                            position: "0 0" // 所在背景图位置坐标
                        }
                    },
                    // 新增 Emoji 背景图 url
                    url: "//cdn.ronghub/thinking-face.png"
                }
            },
            imEmojiList: "",
            senderId: "",
            senderName: "",
            targetId: "",
            targetName: "",
            targetList: [],
            selectEmojiHtml: "",
            hasHistoryMsg: true,
            totalUnreadNum: 0, // 所有未读计数
            historyMsgLoaded: {
                // 加载过
            },
            firstMsg: {},
            lastMsg: {},
            unreadCount: {},
            imTOkenCount:0,
        };
    },
    computed: {},
    created: function() {
        this.appkey = this.getConfigVal("system", "rong_appkey");
        let that = this;
        this.imClientInit(this.appkey);
        bus.$on("handleTarget", function(val) {
            if (that.$store.state.user.isLogin) {
                that.senderName = that.$store.state.user.user.name;
            } else {
                bus.$emit("needlogin");
            }

            var f = function(){
                if (val != -1) {
                    that.imIsShow = true;
                    that.targetId = val.targetId;
                    that.targetName = val.targetName;
                    that.targetIdInTargetList(val.targetId, val.targetName);
                    setTimeout(() => {
                        that.showTargetMsgBody(val.targetId, val.targetName);
                    }, 100);
                } else {
                    // 切换显示
                    that.imIsShow = !that.imIsShow;
                }
            }

            if (!that.loaded) {
                that.getConversationList(f);
                that.loaded = true;
            } else {
                f();
            }
            
        });
    },
    watch: {
        totalUnreadNum: {
            handler: function(val, old) {
                console.log(val)
                console.log(old)
                if (val != old) {
                    bus.$emit("sendTotalUnreadNum", val);
                }
            }
        }
    },
    mounted: function() {},
    methods: {
        selectTarget: function(list, index) {
            // 选择对话目标
            this.showTargetMsgBody(list.targetId, list.targetName);
        },
        showTargetMsgBody: function(targetId, targetName) {
            let that = this;
            that.targetId = targetId;
            that.targetName = targetName;
            $(".all-say").hide();
            $("." + that.targetId).show();
            that.hasHistoryMsg = true;
            $(".conversation-list p").removeClass("new-msg");
            let msgBody = $("." + that.targetId)[0];
            // 首次加载历史记录
            if (
                msgBody &&
                msgBody.children.length == 0 &&
                !that.historyMsgLoaded[targetId]
            ) {
                that.getHistoryMsg(true);
                that.historyMsgLoaded[targetId] = true;
            } else {
                if(that.unreadCount[targetId]){
                    that.unreadCount[targetId] = 0;
                    that.clearUnreadNum(targetId);
                }
                that.scrollTargetBottom(targetId);
            }
        },
        scrollTargetBottom: function(targetId){
            $(".imMsg-content").animate(
                {
                    scrollTop:  $("." + targetId)[0].scrollHeight
                },
                200
            );
        },
        selectEmoji: function(emoji) {
            // 选择emoji表情
            let that = this;
            that.mySendMsg += emoji.emoji;
            that.emojiShow = false;
        },
        targetIdInTargetList: function(targetId, targetName) {
            let that = this;
            let len = that.conversationList.length;
            if (len == 0) {
                that.conversationList.unshift({
                    targetId: targetId,
                    targetName: targetName
                });
            } else {
                let index = -1;
                that.conversationList.forEach(function(item, key) {
                    if (item.targetId == targetId) {
                        index = key;
                    }
                });
                console.log(index);
                if (index > -1) {
                    [that.conversationList[index], that.conversationList[0]] = [
                        that.conversationList[0],
                        that.conversationList[index]
                    ];

                    console.log(that.conversationList);
                } else {
                    that.conversationList.unshift({
                        targetId: targetId,
                        targetName: targetName
                    });
                }
            }
        },
        imClientInit: function(appkey) {
            // 初始化im
            let that = this;
            RongIMLib.RongIMClient.init(appkey);
            that.imEmojiInit(that.config);
            that.setConnectionStatusLis(); // 必须设置监听器后,再连接融云服务器,
            that.setOnReceiveMessageLis();
            that.getToken();
        },
        imEmojiInit: function(config) {
            // 初始化表情
            let that = this;
            RongIMLib.RongIMEmoji.init(config);
            that.imEmojiList = RongIMLib.RongIMEmoji.list;
        },
        getToken: function() {
            // 获取token
            let that = this;
            // 获取token值成功后进行connect连接
            if (that.$store.state.user.isLogin) {
                // 用户登录成功后采取获取token
                if (that.$store.state.user.user.imToken) {
                    //先从store找imtoken
                    that.toConnect(that.$store.state.user.user.imToken);
                } else {
                    that.userApi.getImToken({}, function(res) {
                        that.toConnect(res.imToken);
                    });
                }
            }
        },
        setConnectionStatusLis: function() {
            // 设置监听器
            let that = this;
            RongIMClient.setConnectionStatusListener({
                onChanged: function(status) {
                    switch (status) {
                        case RongIMLib.ConnectionStatus.CONNECTED:
                            console.log("链接成功");
                            break;
                        case RongIMLib.ConnectionStatus.CONNECTING:
                            console.log("正在链接");
                            break;
                        case RongIMLib.ConnectionStatus.DISCONNECTED:
                            console.log("断开连接");
                            that.alertMsgShow = true;
                            that.alertMsg = "当前消息回话已断开。";
                            break;
                        case RongIMLib.ConnectionStatus
                            .KICKED_OFFLINE_BY_OTHER_CLIENT:
                            that.alertMsgShow = true;
                            that.alertMsg = "其他页面登录,当前消息回话已断开。";
                            break;
                        case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                            console.log("域名不正确");
                            break;
                        case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                            console.log("网络不可用");
                            break;
                    }
                }
            });
        },
        toConnect: function(token) {
            let that = this;
            RongIMClient.connect(
                token,
                {
                    onSuccess: function(userId) {
                        that.senderId = userId;
                        that.getTotalUnreadNum();
                    },
                    onTokenIncorrect: function() {
                        console.log("token无效");
                        that.imTOkenCount++;
                        if(that.imTOkenCount<2){
                            that.getToken();
                        }
                    },
                    onError: function(errorCode) {
                        let that = this;
                        var info = "";
                        switch (errorCode) {
                            case RongIMLib.ErrorCode.TIMEOUT:
                                that.alertMsgShow = true;
                                that.alertMsg = "服务器连接超时";
                                break;
                            case RongIMLib.ConnectionState
                                .UNACCEPTABLE_PAROTOCOL_VERSION:
                                info = "不可接受的协议版本";
                                break;
                            case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                                info = "appkey不正确";
                                break;
                            case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                                that.alertMsgShow = true;
                                that.alertMsg = "消息服务暂时不可用";
                                break;
                        }
                    }
                }
            );
        },
        toReconnect: function() {
            let that = this;
            let config = {
                // 默认 false, true 启用自动重连,启用则为必选参数
                auto: true,
                // 网络嗅探地址 [http(s)://]cdn.ronghub/RongIMLib-2.2.6.min.js 可选
                url: "cdn.ronghub/RongIMLib-2.2.6.min.js",
                // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选
                rate: [100, 1000, 3000, 6000, 10000]
            };
            RongIMClient.reconnect({
                    onSuccess: function(userId) {
                        that.senderId = userId;
                        that.getConversationList();
                        that.getTotalUnreadNum();
                    },
                    onTokenIncorrect: function() {
                        console.log("token无效");
                        that.getToken();
                    },
                    onError: function(errorCode) {
                        let that = this;
                        var info = "";
                        switch (errorCode) {
                            case RongIMLib.ErrorCode.TIMEOUT:
                                info = "超时";
                                break;
                            case RongIMLib.ConnectionState
                                .UNACCEPTABLE_PAROTOCOL_VERSION:
                                info = "不可接受的协议版本";
                                break;
                            case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                                info = "appkey不正确";
                                break;
                            case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                                info = "服务器不可用";
                                break;
                        }
                    }
                }, config);
        },
        setOnReceiveMessageLis: function() {
            // 消息监听器
            let that = this;
            RongIMClient.setOnReceiveMessageListener({
                // 接收到的消息
                onReceived: function(msg) {
                    var targetId = msg.targetId;
                    // 判断消息类型
                    if (msg) {
                        that.targetIdInTargetList(
                            msg.targetId,
                            msg.content.extra.split(",|")[0]
                        );
                    }
                    that.$nextTick(function() {
                        var renderTime = true;
                        // 如果尾条消息和本消息方向一致且时间戳间隔小于1小时,则不进行时间的渲染
                        if(that.lastMsg[targetId] && that.lastMsg[targetId].messageDirection == msg.messageDirection
                        ){
                            var d1 = new Date(that.lastMsg[targetId].sentTime);
                            var d2 = new Date(msg.sentTime);
                            if(Math.abs(d1.getTime() - d2.getTime())<3600000){
                                renderTime = false;
                            }
                        }
                        $("." + targetId).append(
                            '<div class="say">\
                            <div style="float:left">' + (renderTime ?
                                ('<p style="text-align:left;color:#666;margin:5px;font-size:10px;">' +
                                    new Date(msg.sentTime).format(
                                    "yyyy-MM-dd hh:mm:ss"
                                ) +
                                '</p>') : '') +
                                '<div>\
                                    <img style="height:28px;width:28px;border-radius:14px;margin-right:10px;float:left;" onerror="this.src=\'' + that.getDefaultAvatar() + '\'" src="' + that.getAvartar(msg.senderUserId.slice(2)) + '"></img>\
                                    <p style="width:fit-content;background-color:#eee;padding:5px 10px;border-radius:7px;float:left;max-width:400px;word-wrap:break-word;">' +
                                        msg.content.content +
                                    "</p>\
                                </div>\
                            </div>\
                        </div>"
                        );
                         // 设置尾条消息
                        that.lastMsg[targetId] = {
                            messageDirection: msg.messageDirection,
                            sentTime: msg.sentTime
                        }
                        // 如果首条消息没有 当前消息设为首条消息
                        if(!that.firstMsg[targetId]){
                            that.firstMsg[targetId] = that.lastMsg[targetId];
                        }
                        // $(".all-say").hide();
                        // $("." + that.targetId).show();
                        if(that.targetId == targetId){
                            that.scrollTargetBottom(targetId);
                        }
                    });
                    if (!that.imIsShow) {
                        that.getTotalUnreadNum();
                        that.unreadCount[targetId] = 1;
                    } else {
                        $(".conversation-list p").removeClass("new-msg");
                        $(".list" + targetId + " p").addClass("new-msg");
                        that.clearUnreadNum(targetId);
                    }
                    switch (msg.messageType) {
                        case RongIMClient.MessageType.TextMessage:
                            // message.content.content => 消息内容
                            break;
                        case RongIMClient.MessageType.VoiceMessage:
                            // 对声音进行预加载
                            // message.content.content 格式为 AMR 格式的 base64 码
                            break;
                        case RongIMClient.MessageType.ImageMessage:
                            // message.content.content => 图片缩略图 base64。
                            // message.content.imageUri => 原图 URL。
                            break;
                        case RongIMClient.MessageType
                            .DiscussionNotificationMessage:
                            // message.content.extension => 讨论组中的人员。
                            break;
                        case RongIMClient.MessageType.LocationMessage:
                            // message.content.latiude => 纬度。
                            // message.content.longitude => 经度。
                            // message.content.content => 位置图片 base64。
                            break;
                        case RongIMClient.MessageType.RichContentMessage:
                            // message.content.content => 文本消息内容。
                            // message.content.imageUri => 图片 base64。
                            // message.content.url => 原图 URL。
                            break;
                        case RongIMClient.MessageType
                            .InformationNotificationMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType
                            .ContactNotificationMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType
                            .ProfileNotificationMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType
                            .CommandNotificationMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType.CommandMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType.UnknownMessage:
                            // do something...
                            break;
                        case RongIMClient.MessageType.RegisterMessage:
                            console.log();
                        default:
                        // do something...
                    }
                }
            });
        },
        getTotalUnreadNum: function() {
            let that = this;
            RongIMClient.getInstance().getTotalUnreadCount({
                onSuccess: function(count) {
                    // count => 所有会话总未读数。
                    console.log(count);
                    that.totalUnreadNum = count;
                },
                onError: function(error) {
                    // error => 获取总未读数错误码。
                }
            });
        },
        clearUnreadNum: function(targetId) {
            let that = this;
            var conversationType = RongIMLib.ConversationType.PRIVATE;
            // var targetId = "xxx";
            RongIMClient.getInstance().clearUnreadCount(
                conversationType,
                targetId,
                {
                    onSuccess: function() {
                        // 清除未读消息成功。
                        that.getTotalUnreadNum();
                    },
                    onError: function(error) {
                        // error => 清除未读消息数错误码。
                    }
                }
            );
        },
        getConversationOfTarget() {
            // 获取指定会话
            let that = this;
            var conversationType = 1;
            RongIMLib.RongIMClient.getInstance().getConversation(
                conversationType,
                that.targetId,
                {
                    onSuccess: function(con) {
                        if (con) {
                            console.log(that.targetName);
                            con.conversationTitle = that.targetName;
                            RongIMLib.RongIMClient.getInstance().updateConversation(
                                con
                            );
                            // consoleInfo("updateConversation Success!");
                        }
                    }
                }
            );
        },
        getHistoryMsg(scroll) {
            // 获取历史消息
            let that = this;
            var conversationType = RongIMLib.ConversationType.PRIVATE; //单聊,其他会话选择相应的消息类型即可。
            var timestrap = null; // 默认传 null,若从头开始获取历史消息,请赋值为 0 ,timestrap = 0;
            var count = 20; // 每次获取的历史消息条数,范围 0-20 条,可以多次获取。
            console.log(that.targetId);
            RongIMLib.RongIMClient.getInstance().getHistoryMessages(
                conversationType,
                that.targetId,
                timestrap,
                count,
                {
                    onSuccess: function(list, hasMsg) {
                        that.hasHistoryMsg = hasMsg;
                        let html = "";
                        if (list.length > 0) {
                            for (let i = 0; i < list.length; i++) {
                                var targetId = that.targetId;
                                var msg = list[i];
                                var renderTime = true;
                                // 如果首条消息和本消息方向一致且时间戳间隔小于1小时,则不进行时间的渲染
                                if(that.firstMsg[targetId] && that.firstMsg[targetId].messageDirection == msg.messageDirection
                                ){
                                    var d1 = new Date(that.firstMsg[targetId].sentTime);
                                    var d2 = new Date(msg.sentTime);
                                    if(Math.abs(d1.getTime() - d2.getTime())<3600000){
                                        renderTime = false;
                                    }
                                }
                                if (msg.messageDirection == 1) {
                                    // 表示发送消息
                                    html +=
                                        '<div class="say">\
                                            <div style="float:right;margin-top:10px;">' + (renderTime ?
                                                ('<p style="text-align:right;color:#666;margin:5px;font-size:10px;">' +
                                                    new Date(msg.sentTime).format(
                                                    "yyyy-MM-dd hh:mm:ss"
                                                ) +
                                                '</p>') : '') +
                                                '<div>\
                                                    <img style="height:28px;width:28px;border-radius:14px;margin-left:10px;float:right;" onerror="this.src=\'' + that.getDefaultAvatar() + '\'" src="' + that.getAvartar(msg.senderUserId.slice(2)) + '"></img>\
                                                    <p style="width:fit-content;background-color:#05a0fa;color:white;padding:5px 10px;border-radius:7px;float:right;word-wrap:break-word;max-width:400px;">' +
                                                        msg.content.content +
                                                    '</p>\
                                                </div>\
                                            </div>\
                                        </div>';
                                } else {
                                    // 接收消息
                                    html +=
                                        '<div class="say">\
                                            <div style="float:left;margin-top:10px;">'+ (renderTime ?
                                                ('<p style="text-align:left;color:#666;margin:5px;font-size:10px;">' +
                                                    new Date(msg.sentTime).format(
                                                    "yyyy-MM-dd hh:mm:ss"
                                                ) +
                                                '</p>') : '') +
                                                '<div>\
                                                    <img style="height:28px;width:28px;border-radius:14px;margin-right:10px;float:left;" onerror="this.src=\'' + that.getDefaultAvatar() + '\'" src="' + that.getAvartar(msg.senderUserId.slice(2)) + '"></img>\
                                                    <p style="width:fit-content;background-color:#eee;padding:5px 10px;border-radius:7px;float:left;max-width:400px;word-wrap:break-word;">' +
                                                        msg.content.content +
                                                    "</p>\
                                                </div>\
                                            </div>\
                                        </div>";
                                }
                                // 设置首条消息
                                that.firstMsg[targetId] = {
                                    messageDirection: msg.messageDirection,
                                    sentTime: msg.sentTime
                                }
                                // 如果尾条消息没有 当前消息设为尾条消息
                                if(!that.lastMsg[targetId]){
                                    that.lastMsg[targetId] = that.firstMsg[targetId];
                                }
                            }
                            var win = $("." + targetId);
                            win.prepend(html);
                            $(".list" + targetId + " p").removeClass(
                                "new-msg"
                            );
                            console.log("scorll:"+scroll)
                            if (scroll) {
                                that.scrollTargetBottom(targetId);
                            }
                        }
                        if (that.imIsShow) {
                            that.clearUnreadNum(that.targetId);
                        } else {
                            that.getTotalUnreadNum();
                        }
                    },
                    onError: function(error) {
                        console.log("GetHistoryMessages,errorcode:" + error);
                    }
                }
            );
        },
        getnameById: function(userId) {
            let that = this;
            that.userApi.getUserNameById({ userId: userId }, function(res) {
                console.log(res.name);
                return res.name;
            });
        },
        getDefaultAvatar(){
            return this.getConfigVal("system", "avatarPath") + this.getConfigVal("home", "defaultAvartar");
        },
        getConversationList: function(callback) {
            // 获取会话列表
            let that = this;
            RongIMClient.getInstance().getConversationList(
                {
                    onSuccess: function(list) {
                        // list => 会话列表集合。
                        console.log(list);
                        if (list.length > 0) {
                            console.log(list[0].targetId);
                            let newList = [];
                            list.forEach(function(item, key) {
                                newList.push({
                                    targetId: item.targetId,
                                    targetName:
                                        item.latestMessage.messageDirection == 1
                                            ? item.latestMessage.content.extra.split(
                                                  ",|"
                                              )[1]
                                            : item.latestMessage.content.extra.split(
                                                  ",|"
                                              )[0]
                                });
                            });
                            that.conversationList = newList;
                        }
                        if(callback){
                            callback();
                        }
                    },
                    onError: function(error) {
                        // do something...
                    }
                },
                null
            );
        },
        sendMsg: function() {
            // 发送消息
            let that = this;
            if (!that.mySendMsg) {
                return;
            }
            var mySendMsg = that.mySendMsg
                .replace(/\r\n/g, "<br>")
                .replace(/\n/g, "<br>");
            var sndMessage = new RongIMLib.TextMessage({
                content: RongIMLib.RongIMEmoji.emojiToHTML(mySendMsg),
                extra: that.senderName + ",|" + that.targetName
            });
            var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
            var targetId = that.targetId; // 目标 Id
            RongIMClient.getInstance().sendMessage(
                conversationtype,
                targetId,
                sndMessage,
                {
                    onSuccess: function(msg) {
                        console.log(msg);
                        var targetId = that.targetId;
                        var renderTime = true;
                        // 如果尾条消息和本消息方向一致且时间戳间隔小于1小时,则不进行时间的渲染
                        if(that.lastMsg[targetId] && that.lastMsg[targetId].messageDirection == msg.messageDirection
                        ){
                            var d1 = new Date(that.lastMsg[targetId].sentTime);
                            var d2 = new Date(msg.sentTime);
                            if(Math.abs(d1.getTime() - d2.getTime())<3600000){
                                renderTime = false;
                            }
                        }
                        //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                        // let s= new Date().getTimeOfLocal(message.sentTime)
                        $("." + that.targetId).append(
                            '<div class="say">\
                                <div style="float:right;margin-top:10px;">' + (renderTime ?
                                    ('<p style="text-align:right;color:#666;margin:5px;font-size:10px;">' +
                                        new Date(msg.sentTime).format(
                                        "yyyy-MM-dd hh:mm:ss"
                                    ) +
                                    '</p>') : '') +
                                    '<div>\
                                        <img style="height:28px;width:28px;border-radius:14px;margin-left:10px;float:right;" onerror="this.src=\'' + that.getDefaultAvatar() + '\'" src="' + that.getAvartar(msg.senderUserId.slice(2)) + '"></img>\
                                        <p style="background-color:#05a0fa;color:white;padding:5px 10px;border-radius:7px;float:right;max-width:400px;word-wrap:break-word;">' +
                                            RongIMLib.RongIMEmoji.emojiToHTML(mySendMsg) +
                                        '</p>\
                                    </div>\
                                </div>\
                            </div>'
                        );
                        // document.querySelector('.'+that.targetId)[0].scrollIntoView(true);
                        var divscrollHeight = $("." + that.targetId)[0];
                        that.scrollTargetBottom(targetId);
                        that.mySendMsg = "";
                        // 设置尾条消息
                        that.lastMsg[targetId] = {
                            messageDirection: msg.messageDirection,
                            sentTime: msg.sentTime
                        }
                        // 如果首条消息没有 当前消息设为首条消息
                        if(!that.firstMsg[targetId]){
                            that.firstMsg[targetId] = that.lastMsg[targetId];
                        }
                    },
                    onError: function(errorCode, message) {
                        var info = "";
                        switch (errorCode) {
                            case RongIMLib.ErrorCode.TIMEOUT:
                                info = "超时";
                                break;
                            case RongIMLib.ErrorCode.UNKNOWN:
                                info = "未知错误";
                                break;
                            case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                                info = "在黑名单中,无法向对方发送消息";
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                                info = "不在讨论组中";
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_GROUP:
                                info = "不在群组中";
                                break;
                            case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                                info = "不在聊天室中";
                                break;
                            default:
                                info = x;
                                break;
                        }
                        console.log("发送失败:" + info);
                    }
                }
            );
        }
    }
};
</script>
<style scoped>
/* 滚动条样式 */
.imMsg-content::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 4px;
}
.imMsg-content::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 10px rgba(255, 255, 255);
    /* background: rgba(0,0,0,0.2); */
    background: white;
}
.imMsg-content::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 10px rgba(255, 255, 255);
    border-radius: 0;
    /* background: rgba(0,0,0,0.1); */
    background: white;
}

.closeim-btn {
    float: right;
    text-align: center;
    cursor: pointer;
}
.say::after {
    content: "";
    display: block;
    clear: both;
}
.im {
    position: fixed;
    right: 80px;
    bottom: 0px;
    z-index: 100000;
    background-color: white;
    width: 800px;
    height: 600px;
    border: 1px solid #ccc;
}
.im-left {
    overflow-y: auto;
    float: left;
    width: 200px;
    border-right: 1px solid #ccc;
    height: 600px;
    background-color: #eee;
}
.im-border {
    border-bottom: 1px solid #ccc;
    background-color: white;
    padding: 10px;
    color: #888;
}
.im-border img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    vertical-align: middle;
}
li div.active {
    background-color: #409eff;
    color: white;
}
li p.new-msg::after {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    background-color: #ef2f23;
    vertical-align: baseline;
    border-radius: 50%;
    margin: 0 5px;
}
</style>

注意: 1、连接融云必须在执行 RongIMLib.RongIMClient.init(appkey); 之后调用; 2、除监听以外所有方法都必须在 connect成功之后调用 3、获取对话列表渲染页面时逻辑比较复杂, 最后实现的效果是这样的

转载于:https://my.oschina/u/4019503/blog/3027558

更多推荐

vue项目集成融云webIM即时通讯