info.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. <template>
  2. <mobile-frame>
  3. <view class="main">
  4. <view class="one">
  5. <!-- 聊天内容 -->
  6. <scroll-view class="scroll-view" scroll-y="true" scroll-with-animation="true"
  7. :scroll-into-view="scrollToView" refresher-enabled="true" :refresher-triggered="triggered"
  8. @refresherrefresh="getFresh">
  9. <view class="list-scroll-view">
  10. <view class="chat-ls" v-for="(item,index) in msgList" :key="index" :id="'msg'+ index">
  11. <view class="chat-time" v-if="item.time != ''">
  12. {{item.time}}
  13. </view>
  14. <view class="msg-m msg-left" v-if="item.speaker !=  user._id">
  15. <image @tap="toShop()" class="user-img"
  16. :src="shop.logo&&shop.logo.length>0?shop.logo[0].url:''">
  17. </image>
  18. <!-- 文字 -->
  19. <view class="message" v-if="item.msg_type =='0'">                           
  20. <view class="msg-text">{{item.content}}</view>
  21. </view>
  22. <!-- 图像 -->
  23. <view class="message img" v-else-if="item.msg_type =='1'"
  24. @tap="previewImg(item.content)">
  25. <image :src="item.content" class="msg-img" mode="widthFix"></image>
  26. </view>
  27. </view>
  28. <view class="msg-m msg-right" v-if="item.speaker == user._id">
  29. <image class="user-img" :src="user.icon&&user.icon.length>0?user.icon[0].url:''">
  30. </image>
  31. <!-- 文字 -->
  32. <view class="message" v-if="item.msg_type =='0'">
  33. <view class="msg-text">{{item.content}}</view>
  34. </view>
  35. <!-- 图像 -->
  36. <view class="message img" v-else-if="item.msg_type =='1'"
  37. @tap="previewImg(item.content)">
  38. <image :src="item.content" class="msg-img" mode="widthFix"></image>
  39. </view>
  40. </view>
  41. </view>
  42. </view>
  43. </scroll-view>
  44. </view>
  45. <view class="two">
  46. <submit_1 @inputs="inputs" @heights="heights"></submit_1>
  47. </view>
  48. </view>
  49. </mobile-frame>
  50. </template>
  51. <script>
  52. import moment from 'moment';
  53. import submit_1 from './components/submit_1.vue';
  54. export default {
  55. components: {
  56. submit_1,
  57. },
  58. data() {
  59. return {
  60. // 用户信息
  61. user: {},
  62. // 房间号id
  63. id: '',
  64. // 店铺信息
  65. shop: {},
  66. // 历史记录
  67. msgList: [],
  68. total: 0,
  69. skip: 0,
  70. limit: 10,
  71. page: 0,
  72. // 判断是否跳到最后一条
  73. is_bottom: true,
  74. // 判断是否下拉刷新复位
  75. triggered: false,
  76. scrollToView: '', //滑动最后一条信息
  77. isSocketOpen: false, //socket是否打开
  78. pingpangTimes: null, //socket心跳计时器
  79. timeoutnum: null, //断开 重连倒计时,
  80. closeType: 1, //断开判断:0代表不重连,1代表重连
  81. };
  82. },
  83. onShow() {
  84. const that = this;
  85. // that.initWebpack(); //初始化
  86. that.closeType = 1 //进入改为1,代表如果断开链接自动重连
  87. that.clearPage();
  88. if (that.id) that.search()
  89. },
  90. onLoad: async function(e) {
  91. const that = this;
  92. that.$set(that, `id`, e.id);
  93. that.watchlogin();
  94. },
  95. beforeDestroy() {
  96. const that = this;
  97. that.closeType = 0 //离开页面前改为0,代表离开后断开链接不再重连
  98. clearInterval(that.pingpangTimes) //清除socket心跳定时器
  99. uni.closeSocket() //关闭socket
  100. },
  101. methods: {
  102. // 监听用户是否登录
  103. watchlogin() {
  104. const that = this;
  105. uni.getStorage({
  106. key: 'token',
  107. success: function(res) {
  108. let user = that.$jwt(res.data);
  109. if (user) that.$set(that, `user`, user)
  110. }
  111. })
  112. },
  113. // 查询历史记录
  114. async search() {
  115. const that = this;
  116. let info = {
  117. skip: that.skip,
  118. limit: that.limit,
  119. room: that.id
  120. }
  121. let res;
  122. res = await that.$api(`/chatRecord`, `GET`, {
  123. ...info,
  124. }, 'chat');
  125. if (res.errcode == '0') {
  126. let msgList = [...res.data, ...that.msgList];
  127. msgList.sort(function(a, b) {
  128. return a.time > b.time ? 1 : -1;
  129. });
  130. that.$set(that, `msgList`, msgList);
  131. that.$set(that, `total`, res.total)
  132. } else {
  133. uni.showToast({
  134. title: res.errmsg,
  135. icon: 'none'
  136. })
  137. }
  138. // 查询房间信息
  139. // 如果是下拉刷新聊天记录不请求房间信息
  140. if (that.is_bottom == true) {
  141. res = await that.$api(`/room/${that.id}`, `GET`, {}, 'chat')
  142. if (res.errcode == '0') {
  143. that.$set(that, `shop`, res.data && res.data.shop);
  144. if (res.data && res.data.shop && res.data.shop.name) {
  145. uni.setNavigationBarTitle({
  146. title: res.data.shop.name
  147. });
  148. }
  149. } else {
  150. uni.showToast({
  151. title: res.errmsg,
  152. icon: 'none'
  153. })
  154. }
  155. }
  156. let id = that.msgList.filter(i => {
  157. return i.speaker != that.user._id;
  158. })
  159. let ids = id.map(i => {
  160. return i._id
  161. })
  162. // 信息已读
  163. res = await that.$api(`/chatRecord/read`, `POST`, {
  164. ids
  165. }, 'chat')
  166. if (res.errcode == '0') {
  167. console.log(res);
  168. } else {
  169. uni.showToast({
  170. title: res.errmsg,
  171. icon: 'none'
  172. })
  173. }
  174. // 跳转到最后一条数据 与前面的:id进行对照
  175. // 如果是下拉刷新聊天记录不跳到最后一条
  176. if (that.is_bottom == true) {
  177. that.$nextTick(function() {
  178. that.scrollToView = 'msg' + (that.msgList.length - 1)
  179. })
  180. }
  181. },
  182. // 初始化websocket链接
  183. initWebpack() {
  184. const that = this;
  185. let config = that.$config;
  186. let url = `wss://${config.stompUrl}/ws/exchange/t_m_dev_local/635f82e62df39d4755a25a4a`;
  187. //创建新的socket连接前确保旧的已关闭
  188. uni.closeSocket()
  189. uni.connectSocket({
  190. url,
  191. success: function(res) {
  192. console.log(res, 's');
  193. },
  194. fail: function(err) {
  195. console.log(err, 'e');
  196. }
  197. });
  198. //监听socket打开
  199. uni.onSocketOpen(() => {
  200. that.isSocketOpen = true
  201. console.log('WebSocket连接已打开!');
  202. })
  203. //监听socket关闭
  204. uni.onSocketClose(() => {
  205. that.isSocketOpen = false
  206. //断开链接时判断
  207. if (that.closeType == 0) return
  208. that.reconnect(); //重连
  209. console.log('WebSocket连接已关闭!');
  210. })
  211. //监听socket错误
  212. uni.onSocketError(() => {
  213. that.isSocketOpen = false
  214. //断开链接时判断
  215. if (that.closeType == 0) return
  216. that.reconnect(); //重连
  217. console.log('WebSocket连接打开失败');
  218. })
  219. //监听socket消息
  220. uni.onSocketMessage((res) => {
  221. let info = JSON.parse(res.data)
  222. if (info.cadmin != 5) {
  223. that.msgList = that.msgList.concat(info) //获取实时聊天内容信息
  224. }
  225. })
  226. //先确保清除了之前的心跳定时器
  227. clearInterval(that.pingpangTimes)
  228. //每过一段时间发送一次心跳,发送Ping,服务器会反馈pong,这样操作以保持socket一直是连接状态,防止断开连接,心跳停止
  229. that.pingpangTimes = setInterval(() => {
  230. uni.sendSocketMessage({
  231. data: "ping",
  232. success: () => {},
  233. fail: () => {
  234. that.isSocketOpen = false
  235. }
  236. });
  237. }, 60000)
  238. },
  239. //重新连接
  240. reconnect() {
  241. const that = this;
  242. //防止重复链接
  243. if (that.isSocketOpen) return;
  244. that.isSocketOpen = true;
  245. //没连接上会一直重连,设置延迟避免请求过多
  246. that.timeoutnum && clearTimeout(that.timeoutnum);
  247. that.timeoutnum = setTimeout(function() {
  248. that.initWebpack(); //新连接
  249. }, 5000);
  250. },
  251. // 进行图片的预览
  252. previewImg(e) {
  253. const that = this;
  254. // 预览图片
  255. uni.previewImage({
  256. current: 0,
  257. urls: [e],
  258. longPressActions: {
  259. itemList: ['发送给朋友', '保存图片', '收藏'],
  260. success: function(data) {
  261. console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
  262. },
  263. fail: function(err) {
  264. console.log(err.errMsg);
  265. }
  266. }
  267. });
  268. },
  269. //接受输入内容
  270. async inputs(e) {
  271. const that = this;
  272. let user = that.user
  273. if (user._id) {
  274. //时间间隔处理
  275. let data = {
  276. "room": that.id,
  277. "speaker": user._id,
  278. "content": e.message,
  279. "time": moment().format('YYYY-MM-DD HH:mm:ss'),
  280. "msg_type": e.type
  281. };
  282. // 发送给服务器消息
  283. // if (that.isSocketOpen) { //socket连接正常
  284. let res = await that.$api(`/chatRecord`, `POST`, data, 'chat');
  285. if (res.errcode == '0') {
  286. that.msgList.push(res.data);
  287. // data = JSON.stringify(data) //后端规定的评论数据格式:json转字符串
  288. // uni.sendSocketMessage({
  289. // data,
  290. // success: () => {
  291. // uni.showToast({
  292. // title: '发送成功',
  293. // icon: 'none'
  294. // })
  295. // },
  296. // fail: () => {
  297. // uni.showToast({
  298. // title: '发送失败,请稍后再试或重新进入此页面尝试',
  299. // icon: 'none'
  300. // })
  301. // }
  302. // });
  303. } else {
  304. uni.showToast({
  305. title: res.errmsg,
  306. icon: 'none'
  307. })
  308. }
  309. // } else { //socket已断开
  310. // uni.showToast({
  311. // title: '聊天断开啦,请重新进入此页面尝试 ~',
  312. // icon: 'none'
  313. // })
  314. // }
  315. // 跳转到最后一条数据 与前面的:id进行对照
  316. that.$nextTick(function() {
  317. that.scrollToView = 'msg' + (that.msgList.length - 1)
  318. })
  319. } else {
  320. uni.showToast({
  321. title: '未登录账号无法发送消息 ,请及时登录!',
  322. icon: 'none'
  323. })
  324. }
  325. },
  326. // 店铺
  327. toShop() {
  328. uni.navigateTo({
  329. url: `/pagesHome/shop/index`
  330. })
  331. },
  332. //输入框高度
  333. heights(e) {
  334. const that = this;
  335. that.goBottom();
  336. },
  337. // 滚动到底部
  338. goBottom() {
  339. const that = this;
  340. that.scrollToView = '';
  341. that.$nextTick(function() {
  342. that.scrollToView = 'msg' + (that.msgList.length - 1)
  343. })
  344. },
  345. // 下拉刷新分页
  346. getFresh(e) {
  347. const that = this;
  348. that.triggered = true;
  349. let list = that.msgList;
  350. let limit = that.limit;
  351. setTimeout(() => {
  352. if (that.total > list.length) {
  353. uni.showLoading({
  354. title: '加载中',
  355. mask: true
  356. })
  357. let page = that.page + 1;
  358. that.$set(that, `page`, page)
  359. let skip = page * limit;
  360. that.$set(that, `skip`, skip)
  361. that.$set(that, `is_bottom`, false)
  362. that.search();
  363. uni.hideLoading();
  364. } else {
  365. uni.showToast({
  366. title: `没有更多聊天记录了`,
  367. icon: 'none'
  368. })
  369. }
  370. that.triggered = false;
  371. }, 1000)
  372. },
  373. clearPage() {
  374. const that = this;
  375. that.$set(that, `msgList`, [])
  376. that.$set(that, `skip`, 0)
  377. that.$set(that, `limit`, 10)
  378. that.$set(that, `page`, 0)
  379. },
  380. }
  381. }
  382. </script>
  383. <style lang="scss">
  384. .main {
  385. display: flex;
  386. flex-direction: column;
  387. width: 100vw;
  388. height: 100vh;
  389. overflow: hidden;
  390. .one {
  391. position: relative;
  392. flex-grow: 1;
  393. .scroll-view {
  394. .chat-ls {
  395. padding: 0 2vw;
  396. .chat-time {
  397. font-size: 24rpx;
  398. color: rgba(39, 40, 50, 0.3);
  399. line-height: 34rpx;
  400. padding: 10rpx 0rpx;
  401. text-align: center;
  402. }
  403. .msg-m {
  404. display: flex;
  405. padding: 20rpx 0;
  406. .user-img {
  407. flex: none;
  408. width: 80rpx;
  409. height: 80rpx;
  410. border-radius: 40rpx;
  411. border: 1px solid #c0c0c0;
  412. }
  413. .message {
  414. flex: none;
  415. max-width: 480rpx;
  416. }
  417. .img {
  418. margin: 0 20rpx 0 0;
  419. }
  420. .msg-text {
  421. font-size: 32rpx;
  422. color: rgba(39, 40, 50, 1);
  423. line-height: 44rpx;
  424. padding: 18rpx 24rpx;
  425. }
  426. .msg-img {
  427. max-width: 400rpx;
  428. border-radius: 20rpx;
  429. }
  430. }
  431. .msg-left {
  432. flex-direction: row;
  433. .msg-text {
  434. margin-left: 16rpx;
  435. background-color: #f1f1f1;
  436. border-radius: 0rpx 20rpx 20rpx 20rpx;
  437. }
  438. .ms-img {
  439. margin-left: 16rpx;
  440. }
  441. }
  442. .msg-right {
  443. flex-direction: row-reverse;
  444. .msg-text {
  445. margin-right: 16rpx;
  446. background-color: rgba(255, 228, 49, 0.8);
  447. border-radius: 20rpx 0rpx 20rpx 20rpx;
  448. }
  449. .ms-img {
  450. margin-right: 16rpx;
  451. }
  452. }
  453. }
  454. }
  455. }
  456. .two {
  457. background-color: #f0f0f0;
  458. border-top: 1px solid rgba(39, 40, 50, 0.1);
  459. }
  460. }
  461. .scroll-view {
  462. position: absolute;
  463. top: 0;
  464. left: 0;
  465. right: 0;
  466. bottom: 0;
  467. .list-scroll-view {
  468. display: flex;
  469. flex-direction: column;
  470. }
  471. }
  472. </style>