info.vue 11 KB

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