当前位置: 首页 > news >正文

vue 加 websocket 聊天

<template><div style="height: 100%; width: 100%; background-color: #fff"><div class="wrap"><!-- 头部 --><div class="titleBox"><imgsrc="@/assets/image/avatar.png"style="argin: 10px 20px 10px 20px;width: 40px;height: 40px;"class="head_portrait"/><span style="color: #fff;font-size: 15px;">官方客服</span></div><!-- 底部 --><div class="infoBox"><!-- 左边用户列表 --><div class="userList"><div class="searchBox"><el-input  placeholder="请输入内容" v-model="search" class="input-with-select" size="mini" @input="inquire"><i  class="el-icon-search el-input__icon" slot="suffix" @click="handleIconClick"  /></el-input>
<!--            <el-button-->
<!--              icon="el-icon-plus"-->
<!--              size="mini"-->
<!--              type="primary"-->
<!--              @click="dialogVisible = true"-->
<!--            ></el-button>--></div><div class="userListBox" ref="scrollUserBox" id="userBox"><div v-if="list!=null && list.length > 0"  v-for="(item, index) in list" :key="index"@click="getAct(item, index)" :class="item.opposUserId == act ? 'userFlexAct' : 'userFlex'" ><el-badge :hidden="item.unreadCount ==0" :value="item.unreadCount" :max="99" class="item"><div><img  :src="item.avatar"   class="head_portrait2"  style="margin-left: 20px ; "  /></div></el-badge><div style="margin-right: 10px;"></div><div style="margin-right: 40px"><div style="color: #565656" class="nickName">{{ item.nickName }}</div><div class="userInfo" v-if="item.messageType==1" >{{item.message}}</div><div class="userInfo" v-if="item.messageType==2" >[商品]</div><div class="userInfo" v-if="item.messageType==3" >[图片]</div><div class="userInfo" v-if="item.messageType==4" >[订单]</div></div><div style="margin-right: 10px; font-size: 14px; color: #ccc">{{ formatDate(item.createTime) }}</div></div></div></div><!-- 右边输入框和信息展示 --><div class="infoList"><!-- 信息 --><div class="infoTop" ref="scrollBox" id="box"><div  v-for="(item, index) in info" :key="index"><!-- 显示时间信息 --><div class="chatInfoRight1 " v-if="shouldShowTime(index)">{{ formatDate1(item.createTime) }}</div><div :class="(item.fromUserId == item.userId && item.fromUserType != 1) ?   'chatInfoRight' :'chatInfoLeft' ">
<!--                <img :src="item.avatar" alt="头像" class="head_portrait2" />--><img :src="(item.fromUserId == item.userId && item.fromUserType != 1) ?  require('@/assets/image/avatar.png') : item.avatar" class="head_portrait2" style="margin-left: 20px;" /><div :class="(item.fromUserId == item.userId && item.fromUserType != 1) ?  'chatRight' : 'chatLeft'"><!-- 文字 --><div class="text" v-if="item.messageType==1" >{{item.message}}</div><!-- 商品 --><div v-if="item.messageType==2" class="text"><!--                  @click="openUrl(`/pages/goodsDetail?id=${parseMessage(item.message).productId}`)"--><div class="goods1"style="width: 200px;height: 70px;margin: 0 auto;background-color: #FFF;display: flex; "><image-preview :src="item.message" :width="60" :height="60"/><div class="right1"style="flex: 1;margin: auto 0;height: 60px;margin-left: 10px;"><div style="color: #333;height: 30px;line-height: 30px;     font-size: 14px; " class="right_title">{{parseMessage(item.message).productName}}</div><div style="height: 30px;color: #ff0000;line-height: 30px;    font-size: 12px;">¥{{parseMessage(item.message).merchantPrice}}</div></div></div></div><!-- 图片 --><div v-if="item.messageType==3" class="text"><image-preview :src="item.message" :width="70" :height="70"/></div></div></div></div></div><!-- 输入框 --><div class="infoBottom"><div class="infoIcon"><mesImg v-if='isshow==1?true:false'  v-model="imgUrl"/>
<!--              <i @click="extend('发送商品')" class="el-icon-sell"></i>-->
<!--              <i @click="extend('设置')" class="el-icon-setting"></i>-->
<!--              <i @click="extend('聊天记录')" class="el-icon-chat-dot-round"></i>-->
<!--              <i @click="extend('更多选项')" class="el-icon-more-outline"></i>--></div><textarea   maxlength="255"show-word-limittype="textarea"class="infoInput"v-model="textarea"@keydown.enter.exact="handlePushKeyword($event)"@keyup.ctrl.enter="lineFeed":disabled='isshow==1?false:true'/><div class="fasong" @click="setUp(1)" v-show="isshow==1?true:false">发送</div></div></div></div></div><!-- 搜索框边 + 号弹框 --><el-dialogtitle="选择需要添加的联系人":visible.sync="dialogVisible"width="30%":modal="false"><span>自定义页面,还没想好写什么功能</span><span slot="footer" class="dialog-footer"><el-button @click="dialogVisible = false">取 消</el-button><el-button type="primary" @click="dialogVisible = false">确 定</el-button></span></el-dialog></div>
</template><script>
import {getMesList,getMesInfo} from "@/api/ums/umsUser";
import axios from 'axios'
export default {watch: {imgUrl(newVal, oldVal) {if (newVal) {this.textarea =this.$constants.baseURL + this.imgUrl;this.setUp(3);}},},data() {return {socket: null,imgUrl: "",queryParams:{pageNum: 1,pageSize: 10,userId:this.$store.getters.userId,userType:2,},queryParamsUser:{pageNum: 1,pageSize: 10,userId:this.$store.getters.userId,userType:2,},// 在线状态state: 1,//搜索用户search: "",user: "",info: [],list:[],total:0,userIdserTotal:0,//用户点击选中变色act: Number,// 加号弹框dialogVisible: false,//历史信息userInfoList: [],//输入框textarea: "",//滚动条距离顶部距离scrollTop: 0,//滚动条距离顶部距离scrollUserTop: 0,//发送和输入显隐isshow:0};},created() {this.socket = new WebSocket('ws://192.168.1.140:9092/front/websocket/2:'+this.$store.getters.userId); // 替换成你的WebSocket服务器地址this.socket.onmessage = this.handleMessage;this.handleMesList()// this.setUserPageScrollTo()},methods: {// 计算是否显示时间信息的函数shouldShowTime(index) {if (index === 0) {return true; // 第一条消息肯定要显示时间信息}const currentItem = this.info[index];const prevItem = this.info[index - 1];const currentTime = new Date(currentItem.createTime);const prevTime = new Date(prevItem.createTime);const timeDiff = currentTime - prevTime; // 计算时间差,单位为毫秒const minutesDiff = Math.floor(timeDiff / 1000 / 60); // 转换为分钟return minutesDiff >= 3; // 如果时间差大于等于3分钟,则显示时间信息},// 解析消息字符串为对象parseMessage(message) {try {return JSON.parse(message);} catch (error) {console.error("Error parsing message:", error);return {}; // 返回空对象以避免渲染错误}},handleMessage(event) {try {const message = JSON.parse(event.data);// 判断发的信息是不是当前会话if (this.user.opposUserId == message.userId){this.getAct(this.user);}else {this.queryParams.pageNum = 1this.handleMesList();}// 处理收到的消息// 例如,将消息添加到相应的聊天记录中} catch (error) {// console.error('Received message is not in JSON format:', event.data);}},// 左侧列表handleMesList(){getMesList(this.queryParams).then(response => {this.list = response.rowsthis.total = response.total});// 直接调用不生效:因为你历史数据刚给,渲染的时候盒子高度还没有成型,所以直接调用拿不到,用个定时器让他在下一轮循环中调用,盒子就已经生成了this.$nextTick(() => { // 一定要用nextTickthis.setUserPageScrollTo();//页面滚动条距离顶部高度等于这个盒子的高度this.$refs.scrollUserBox.scrollUserTop = this.$refs.scrollUserBox.scrollHeight;})},//切换客服状态uploadState(state) {if (state !== 4) {this.state = state;} else {this.$confirm("是否退出登录?", "提示", {confirmButtonText: "确定",cancelButtonText: "取消",type: "warning",}).then(() => {this.$message({type: "success",message: "退出成功!",});}).catch(() => {this.$message({type: "info",message: "已取消退出",});});}},//搜索iconhandleIconClick() {alert("搜索");console.log(1);},//点击用户getAct(val) {console.log(val,11)this.isshow=1// 点击用户切换数据时先清除监听滚动事件,防止出现没有历史数据的用户,滚动条为0,会触发滚动事件this.$refs.scrollBox.removeEventListener("scroll", this.srTop);//点击变色this.act = val.opposUserId;//清空消息数组// this.info = [];this.queryParamsUser.toUserId = val.opposUserIdthis.queryParamsUser.pageNum = 1getMesInfo(this.queryParamsUser).then(response => {this.info = response.rowsthis.userTotal = response.totalthis.queryParams.pageNum = 1this.handleMesList()// 直接调用不生效:因为你历史数据刚给,渲染的时候盒子高度还没有成型,所以直接调用拿不到,用个定时器让他在下一轮循环中调用,盒子就已经生成了this.$nextTick(() => { // 一定要用nextTickthis.setPageScrollTo();//页面滚动条距离顶部高度等于这个盒子的高度this.$refs.scrollBox.scrollTop = this.$refs.scrollBox.s

相关文章:

  • 人工智能+的广泛应用,已渗透到生活的方方面面
  • Linux基础概念
  • 根据实例逐行分析NIO到底在做什么
  • 安全算法 - 加密算法
  • 【机器学习】《机器学习算法竞赛实战》思考练习(更新中……)
  • C语言编写Linux的Shell外壳
  • C#常见Winform窗体效果
  • SpringBoot+ECharts+Html 地图案例详解
  • 四、Mybatis-查询与删除
  • 内网安全之-kerberos协议
  • 第五篇:3.4 用户归因和受众(User attribution and audience) - IAB/MRC及《增强现实广告效果测量指南1.0》
  • SpringBoot+ECharts+Html 字符云/词云案例详解
  • Redis缓存设计与性能优化【缓存穿透、缓存击穿、缓存雪崩】
  • 【Web】记录Polar靶场<困难>难度题一遍过
  • pytorch中的while for 循环 导出onnx的问题
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • 5、React组件事件详解
  • Gradle 5.0 正式版发布
  • IIS 10 PHP CGI 设置 PHP_INI_SCAN_DIR
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • JS字符串转数字方法总结
  • ReactNativeweexDeviceOne对比
  • sessionStorage和localStorage
  • Spring核心 Bean的高级装配
  • vagrant 添加本地 box 安装 laravel homestead
  • Vue.js 移动端适配之 vw 解决方案
  • Yeoman_Bower_Grunt
  • 阿里云爬虫风险管理产品商业化,为云端流量保驾护航
  • 百度贴吧爬虫node+vue baidu_tieba_crawler
  • 机器学习中为什么要做归一化normalization
  • 来,膜拜下android roadmap,强大的执行力
  • 如何合理的规划jvm性能调优
  • 使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上
  • 网页视频流m3u8/ts视频下载
  • 微信支付JSAPI,实测!终极方案
  • 项目实战-Api的解决方案
  • 【运维趟坑回忆录 开篇】初入初创, 一脸懵
  • PostgreSQL 快速给指定表每个字段创建索引 - 1
  • 通过调用文摘列表API获取文摘
  • ​DB-Engines 11月数据库排名:PostgreSQL坐稳同期涨幅榜冠军宝座
  • #传输# #传输数据判断#
  • $ git push -u origin master 推送到远程库出错
  • (1)Nginx简介和安装教程
  • (11)MSP430F5529 定时器B
  • (9)STL算法之逆转旋转
  • (java)关于Thread的挂起和恢复
  • (Matalb分类预测)GA-BP遗传算法优化BP神经网络的多维分类预测
  • (ZT)出版业改革:该死的死,该生的生
  • (板子)A* astar算法,AcWing第k短路+八数码 带注释
  • (备忘)Java Map 遍历
  • (二)Linux——Linux常用指令
  • (二开)Flink 修改源码拓展 SQL 语法
  • (附源码)ssm经济信息门户网站 毕业设计 141634
  • (论文阅读笔记)Network planning with deep reinforcement learning
  • (七)c52学习之旅-中断