Bootstrap

vue 聊天窗口组件 智能客服 wss协议 长链接

#该文章摘抄于另一名作者 加已优化 原文已经找不到了封装成为自己的业务代码

先上效果图

#需要注意事项

当聊天内容过多 要让过滚动条始终保持在底部

this.$nextTick(() => {
     // dom 元素更新后执行滚动条到底部 否则不生效
     let scrollElem = this.$refs.container;
     scrollElem.scrollTop = scrollElem.scrollHeight
});

然后就是自己发送的在的保持在右边 这里用定位比较麻烦 建议用css这个属性

 direction: rtl;

 但是需要注意如果有符号就有问题  如图

此时需要在父元素加上csss属性就正常了

.mine {
        direction: ltr
}

还有就是打字效果让字一个一个出现 这里采用的后端流形式传输 然后你只要push到数组就ok

if (res.data.code == 0) {
     this.messages[this.messages.length - 1].text.push(res.data.data.answer)
}

话不多说 直接上全部代码 让组件显示的时候 调用方法init

<template>
    <div class="chat-window" v-show="isChat">
        <div class="chat-head">
            <div class="h-left">
                <div class="name">
                </div>
                <div class="title">智能客服</div>
            </div>
            <svg style="cursor: pointer;" @click="changeChat(false)" xmlns="http://www.w3.org/2000/svg" width="29"
                height="29" viewBox="0 0 29 29" fill="none">
                <path d="M7.07129 7.07129L21.2134 21.2134" stroke="#666666" stroke-linecap="round" />
                <path d="M7.07129 21.2139L21.2134 7.07173" stroke="#666666" stroke-linecap="round" />
            </svg>
        </div>
        <!-- 显示聊天消息的容器 -->
        <div class="message-container" ref="container">
            <div v-for="(message, i) in messages" :key="i" class="message">
                <div v-if="message.isMe" class="message_item-inner mine-inner">
                    <img class="image" src="../static/img/ai/Group4.png" alt="">
                    <div class="tag">
                        <svg xmlns="http://www.w3.org/2000/svg" width="11" height="15" viewBox="0 0 11 15" fill="none">
                            <path d="M10.6234 12.0001L0.623371 14.5001L0.123645 0.000458366L10.6234 12.0001Z"
                                fill="#E9EFFF" />
                        </svg>
                    </div>
                    <span class="message-text mine">
                        {{ message.text }}

                    </span>

                </div>
                <div v-else class="message_item-inner" v-show="message.text.length > 0">
                    <img class="image" src="../static/img/ai/Group5.png" alt="">
                    <div class="tag">
                        <svg xmlns="http://www.w3.org/2000/svg" width="11" height="15" viewBox="0 0 11 15" fill="none">
                            <path d="M0.376629 12.0001L10.3766 14.5001L10.8764 0.000458366L0.376629 12.0001Z"
                                fill="#E9EFFF" />
                        </svg>
                    </div>
                    <div class="message-text">
                        <span v-for="(item, k) in message.text" :key="k">{{ item }}</span>

                    </div>
                </div>
            </div>
        </div>
        <!-- 输入消息的表单 -->
        <div class="input-form">
            <div class="inputText">
                <el-input @keyup.enter.native="sendMessage" :disabled="inputTextDis" v-model="inputText"
                    placeholder="请输入关键词进行提问" />
            </div>
            <img class="send" @click="sendMessage" src="../static/img/ai/Group6.png" alt="">
        </div>
    </div>
</template>

<script>
import { GetCallcenterLink } from '@/api/newhome/index.js'
export default {
    data() {
        return {
            inputText: '',
            messages: [
                { text: ['您好,我是AI助手,我能与您聊天互动、回答问题。有什么可以帮到您的吗?'], isMe: false },
            ],
            //ws_token从登录接口里获取
            path: ``,
            ws: {},
            // serverMsg: { text: [], isMe: false },
            inputTextDis: false,
            isChat: false,
            callLink: '',
            ws_token: ''
        };
    },
    methods: {
        changeChat(flag) {
            this.isChat = flag
        },
        //init函数可在页面加载的时候就进行初始化或者根据自己的业务需求在需要打开通讯的时候在进行初始化
        init() {
            // 实例化socket,这里的实例化直接赋值给this.ws是为了后面可以在其它的函数中也能调用websocket方法,例如:this.ws.close(); 完成通信后关闭WebSocket连接
            this.path = `${this.ws_token}`
            this.ws = new WebSocket(this.path)

            //监听是否连接成功
            this.ws.onopen = () => {
                console.log('ws连接状态:' + this.ws.readyState);
                //连接成功则发送一个数据
                //  this.ws.send('连接成功');
            }

            //接听服务器发回的信息并处理展示
            this.ws.onmessage = (data) => {
                let res = JSON.parse(data.data)
                // console.log('接收到来自服务器的消息:', res.data.data.answer);
                this.inputTextDis = res.has_next
                if (res.data.code == 0) {
                    this.messages[this.messages.length - 1].text.push(res.data.data.answer)
                }
                if (!res.has_next && res.data.data.is_risk) {
                    this.messages[this.messages.length - 1].text = res.data.data.answer
                }

                this.$nextTick(() => {
                    // dom 元素更新后执行滚动条到底部 否则不生效
                    let scrollElem = this.$refs.container;
                    scrollElem.scrollTop = scrollElem.scrollHeight
                });
            }

            //监听连接关闭事件
            this.ws.onclose = () => {
                //监听整个过程中websocket的状态
                console.log('ws连接状态:' + this.ws.readyState);
            }

            //监听并处理error事件
            this.ws.onerror = function (error) {
                console.log(error);
            }
        },
        sendMessage() {
            if (this.inputText.trim()) {
                this.messages.push({ id: Date.now(), text: this.inputText, isMe: true });
                const data = {
                    "type": "interface",
                    "name": "show",
                    "params": {
                        "text": this.inputText,
                        "voice": "xiaomei"
                    }
                }
                // this.ws.send(JSON.stringify(data));
                this.messages.push({ text: [], isMe: false })
                this.inputText = '';
                this.$nextTick(() => {
                    // dom 元素更新后执行滚动条到底部 否则不生效
                    let scrollElem = this.$refs.container;
                    scrollElem.scrollTop = scrollElem.scrollHeight
                });
            }
        },
    },
};
</script>

<style scoped lang="scss">
.chat-window {
    width: 470px;
    height: 600px;
    margin: 0 auto;
    position: relative;
    // background: url('../static/img/ai/Group3.png');
    // background-size: 100% 100%;
    background: #fff;
    border-radius: 10px;
    box-shadow: 8px 8px 20px rgba(55, 99, 170, .1), -2px -2px 16px rgba(55, 99, 170, .1);
    overflow: hidden;

    .input-form {
        position: absolute;
        bottom: 28px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 24px;

        .inputText {
            width: 363px;
            height: 44px;
            border-radius: 100px;
            background: #E9EFFF;
            display: flex;
            padding: 0 20px;

            ::v-deep .el-input {
                background: #E9EFFF;
                border: 0;

                .el-input__inner {
                    background: #E9EFFF;
                    width: 100%;
                    height: 100%;
                    border: 0;
                }
            }
        }

        .send {
            margin-left: 20px;
            width: 40px;
            height: 40px;
            cursor: pointer;
        }
    }
}

.chat-head {
    width: 100%;
    height: 54px;
    background: rgba(255, 255, 255, 0.80);
    box-shadow: 0px 4px 4px 2px rgba(232, 235, 243, 0.50);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .h-left {
        display: flex;
        align-items: center;
        padding: 0 16px 0 21px;
        cursor: pointer;

        .name {
            width: 131px;
            height: 32px;
            border-radius: 4px;
            background: rgba(80, 113, 216, 0.10);
            color: #5071D8;
            font-family: Source Han Sans CN;
            font-size: 16px;
            font-style: normal;
            font-weight: 400;
            line-height: 32px;

            img {
                width: 30px;
                height: 30px;
                margin-right: 5px;
            }
        }

        .title {
            color: #000;
            font-family: Source Han Sans CN;
            font-size: 22px;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
            margin-left: 40px;
        }
    }
}

.message-container {
    margin-bottom: 10px;
    width: 100%;
    height: 474px;
    overflow-y: auto;
    padding: 0 18px;

    .message {
        padding: 5px;
        margin-top: 40px;

        // direction: rtl
        .message_item-inner {
            width: 100%;
            display: flex;
            align-items: flex-start;

            .image {
                width: 48px;
                height: 48px;
                margin-right: 8px;

            }
        }

        .mine-inner {
            width: 100%;
            direction: rtl;

            .image {
                margin-right: 0;
                margin-left: 8px;
            }
        }
    }

    .message-text {
        display: inline-block;
        max-width: 290px;
        padding: 10px 20px;
        border-radius: 5px;
        background: #E9EFFF;
        color: #666;
        font-family: Source Han Sans CN;
        font-size: 16px;
        font-weight: 400;
        word-wrap: break-word;
        text-align: left;
        position: relative;

    }

    .tag {
        // position: absolute;
        // left: -10px;
        // top: 12px;
        width: 10px;
        height: 16px;
        margin-top: 8px;
    }

    .mine {
        background-color: #E9EFFF;
        direction: ltr
    }
}
</style>

;