info.vue 12 KB

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