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-else-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. //创建一个socket连接
  188. uni.connectSocket({
  189. url,
  190. success: function(res) {
  191. console.log(res, 's');
  192. },
  193. fail: function(err) {
  194. console.log(err, 'e');
  195. }
  196. });
  197. //监听socket打开
  198. uni.onSocketOpen(() => {
  199. that.isSocketOpen = true
  200. console.log('WebSocket连接已打开!');
  201. })
  202. //监听socket关闭
  203. uni.onSocketClose(() => {
  204. that.isSocketOpen = false
  205. //断开链接时判断
  206. if (that.closeType == 0) return
  207. that.reconnect(); //重连
  208. console.log('WebSocket连接已关闭!');
  209. })
  210. //监听socket错误
  211. uni.onSocketError(() => {
  212. that.isSocketOpen = false
  213. //断开链接时判断
  214. if (that.closeType == 0) return
  215. that.reconnect(); //重连
  216. console.log('WebSocket连接打开失败');
  217. })
  218. //监听socket消息
  219. uni.onSocketMessage((res) => {
  220. let info = JSON.parse(res.data)
  221. if (info.cadmin != 5) {
  222. that.msgList = that.msgList.concat(info) //获取实时聊天内容信息
  223. }
  224. })
  225. //先确保清除了之前的心跳定时器
  226. clearInterval(that.pingpangTimes)
  227. //每过一段时间发送一次心跳,发送Ping,服务器会反馈pong,这样操作以保持socket一直是连接状态,防止断开连接,心跳停止
  228. that.pingpangTimes = setInterval(() => {
  229. uni.sendSocketMessage({
  230. data: "ping",
  231. success: () => {},
  232. fail: () => {
  233. that.isSocketOpen = false
  234. }
  235. });
  236. }, 60000)
  237. },
  238. //重新连接
  239. reconnect() {
  240. const that = this;
  241. //防止重复链接
  242. if (that.isSocketOpen) return;
  243. that.isSocketOpen = true;
  244. //没连接上会一直重连,设置延迟避免请求过多
  245. that.timeoutnum && clearTimeout(that.timeoutnum);
  246. that.timeoutnum = setTimeout(function() {
  247. that.initWebpack(); //新连接
  248. }, 5000);
  249. },
  250. // 进行图片的预览
  251. previewImg(e) {
  252. const that = this;
  253. // 预览图片
  254. uni.previewImage({
  255. current: 0,
  256. urls: [e],
  257. longPressActions: {
  258. itemList: ['发送给朋友', '保存图片', '收藏'],
  259. success: function(data) {
  260. console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
  261. },
  262. fail: function(err) {
  263. console.log(err.errMsg);
  264. }
  265. }
  266. });
  267. },
  268. //接受输入内容
  269. async inputs(e) {
  270. const that = this;
  271. let user = that.user
  272. if (user._id) {
  273. //时间间隔处理
  274. let data = {
  275. "room": that.id,
  276. "speaker": user._id,
  277. "content": e.message,
  278. "time": moment().format('YYYY-MM-DD HH:mm:ss'),
  279. "msg_type": e.type
  280. };
  281. // 发送给服务器消息
  282. // if (that.isSocketOpen) { //socket连接正常
  283. if (!that.id) data.shop = that.shop_id
  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.goBottom();
  317. } else {
  318. uni.showToast({
  319. title: '未登录账号无法发送消息 ,请及时登录!',
  320. icon: 'none'
  321. })
  322. }
  323. },
  324. // 店铺
  325. toShop() {
  326. uni.navigateTo({
  327. url: `/pagesHome/shop/index`
  328. })
  329. },
  330. //输入框高度
  331. heights(e) {
  332. const that = this;
  333. that.goBottom();
  334. },
  335. // 滚动到底部
  336. goBottom() {
  337. const that = this;
  338. that.scrollToView = '';
  339. that.$nextTick(function() {
  340. that.scrollToView = 'msg' + (that.msgList.length - 1)
  341. })
  342. },
  343. // 下拉刷新分页
  344. getFresh(e) {
  345. const that = this;
  346. that.triggered = true;
  347. let list = that.msgList;
  348. let limit = that.limit;
  349. setTimeout(() => {
  350. if (that.total > list.length) {
  351. uni.showLoading({
  352. title: '加载中',
  353. mask: true
  354. })
  355. let page = that.page + 1;
  356. that.$set(that, `page`, page)
  357. let skip = page * limit;
  358. that.$set(that, `skip`, skip)
  359. that.$set(that, `is_bottom`, false)
  360. that.search();
  361. uni.hideLoading();
  362. } else {
  363. uni.showToast({
  364. title: `没有更多聊天记录了`,
  365. icon: 'none'
  366. })
  367. }
  368. that.triggered = false;
  369. }, 1000)
  370. },
  371. clearPage() {
  372. const that = this;
  373. that.$set(that, `msgList`, [])
  374. that.$set(that, `skip`, 0)
  375. that.$set(that, `limit`, 10)
  376. that.$set(that, `page`, 0)
  377. },
  378. }
  379. }
  380. </script>
  381. <style lang="scss">
  382. .main {
  383. display: flex;
  384. flex-direction: column;
  385. width: 100vw;
  386. height: 100vh;
  387. overflow: hidden;
  388. .one {
  389. position: relative;
  390. flex-grow: 1;
  391. .scroll-view {
  392. .chat-ls {
  393. padding: 2vw 2vw 0 2vw;
  394. .chat-time {
  395. font-size: 24rpx;
  396. color: rgba(39, 40, 50, 0.3);
  397. line-height: 34rpx;
  398. padding: 10rpx 0rpx;
  399. text-align: center;
  400. }
  401. .msg-m {
  402. display: flex;
  403. padding: 20rpx 0;
  404. .user-img {
  405. flex: none;
  406. width: 80rpx;
  407. height: 80rpx;
  408. border-radius: 40rpx;
  409. border: 1px solid #c0c0c0;
  410. }
  411. .message {
  412. flex: none;
  413. max-width: 480rpx;
  414. }
  415. .img {
  416. margin: 0 20rpx 0 0;
  417. }
  418. .msg-text {
  419. font-size: 32rpx;
  420. color: rgba(39, 40, 50, 1);
  421. line-height: 44rpx;
  422. padding: 18rpx 24rpx;
  423. word-break: break-all;
  424. }
  425. .msg-img {
  426. max-width: 400rpx;
  427. border-radius: 20rpx;
  428. }
  429. }
  430. .msg-left {
  431. flex-direction: row;
  432. .msg-text {
  433. word-break: break-all;
  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>