chat.vue 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. <template>
  2. <view class="chat-box">
  3. <view class="chat-tips" v-if="postData.loading">
  4. {{postData.loadText}}
  5. </view>
  6. <view class="chat-list">
  7. <view :id="`msg-${item.time}`" v-for="(item,index) in chatList" :key="index">
  8. <view class="chat-item" :class="item.from == nowUserId ? 'push':'pull' ">
  9. <image :src="item.fromUserInfo.avatarUrl" mode="aspectFill" class="avatar"></image>
  10. <view class="content-box">
  11. <view class="content" v-if="item.type === 'text'">{{item.body.text}}</view>
  12. <image :src="item.body.thumbnailUrl" mode="aspectFill"
  13. @tap="previewImage(item.body.originalUrl)" :class="[returnImageClass(item.body)]" v-else>
  14. </image>
  15. </view>
  16. <text class="date">
  17. {{$dayjs(item.time).format('YYYY-MM-DD HH:mm:ss')}}
  18. </text>
  19. </view>
  20. </view>
  21. </view>
  22. <view class="chat-submit">
  23. <input type="text" class="message-content" v-model="message" placeholder="请输入聊天内容"
  24. placeholder-class="message-placeholder" :cursor-spacing="6" />
  25. <view class="send-image send-button" @tap="sendImage">
  26. <uni-icons type="images-filled" color="#8c8c8c" size="24"></uni-icons>
  27. </view>
  28. <view class="send-submit send-button" @tap="send">
  29. <uni-icons type="paperplane-filled" color="#fff" size="24"></uni-icons>
  30. </view>
  31. </view>
  32. </view>
  33. </template>
  34. <script>
  35. import {
  36. YeIMUniSDK,
  37. YeIMUniSDKDefines
  38. } from '@/uni_modules/wzJun1-YeIM-Uni-SDK/js_sdk/yeim-uni-sdk.min.js'
  39. import {
  40. login
  41. } from '@/request/api/chat.js'
  42. import md5 from '@/js_sdk/js-md5/build/md5.min.js';
  43. export default {
  44. data() {
  45. return {
  46. message: '',
  47. chatList: [],
  48. postData: {
  49. rows: 10, //每页数量
  50. page: 1, //页码
  51. flag: true, // 请求开关
  52. loading: true, // 加载中
  53. loadText: '正在获取消息...'
  54. },
  55. nextMessageId: '',
  56. nowUserId: ''
  57. }
  58. },
  59. onUnload() {
  60. YeIMUniSDK.getInstance().removeEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, this.onMessage);
  61. },
  62. onLoad(body) {
  63. YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, this.onMessage);
  64. uni.setNavigationBarTitle({
  65. title: body.userName
  66. });
  67. this.nowUserId = this.$store.getters.user.userId;
  68. this.userId = body.userId;
  69. this.getHistoryMsg();
  70. },
  71. onPageScroll(e) {
  72. if (e.scrollTop < 5) {
  73. this.getHistoryMsg();
  74. }
  75. },
  76. methods: {
  77. returnImageClass(item) {
  78. let w = item.thumbnailWidth,
  79. h = item.thumbnailHeight;
  80. let str = ''
  81. if (w > h) str = 'image-width';
  82. if (w == h) str = 'image-width-height';
  83. if (w < h) str = 'image-height';
  84. return str + ' image-box';
  85. },
  86. onMessage(e) {
  87. let message = e;
  88. if (this.userId != message.conversationId) return;
  89. this.insertMessage(message);
  90. this.$chat.clearConversationUnread(this.userId);
  91. },
  92. insertMessage(message) {
  93. try {
  94. this.chatList.push(message);
  95. setTimeout(() => {
  96. uni.pageScrollTo({
  97. scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
  98. duration: 0
  99. });
  100. }, 200)
  101. } catch (e) {
  102. console.log(e)
  103. }
  104. },
  105. getHistoryMsg() {
  106. if (!this.postData.flag || this.nextMessageId === 'null') {
  107. return; //
  108. }
  109. // 此处用到 ES7 的 async/await 知识,为使代码更加优美。不懂的请自行学习。
  110. let get = async () => {
  111. this.toggleTips();
  112. this.postData.flag = false;
  113. let data = await this.joinHistoryMsg();
  114. // 获取待滚动元素选择器,解决插入数据后,滚动条定位时使用
  115. let selector = '';
  116. if (this.postData.page > 1) {
  117. // 非第一页,则取历史消息数据的第一条信息元素
  118. selector = `#msg-${this.chatList[0].time}`;
  119. } else {
  120. if (data.length > 0) {
  121. // 第一页,则取当前消息数据的最后一条信息元素
  122. selector = `#msg-${data[data.length-1].time}`;
  123. }
  124. }
  125. // 将获取到的消息数据合并到消息数组中
  126. this.chatList = [...data, ...this.chatList];
  127. // 数据挂载后执行,不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
  128. this.$nextTick(() => {
  129. // 设置当前滚动的位置
  130. this.setPageScrollTo(selector);
  131. this.toggleTips(true);
  132. if (data.length < this.postData.rows) {
  133. // 当前消息数据条数小于请求要求条数时,则无更多消息,不再允许请求。
  134. // 可在此处编写无更多消息数据时的逻辑
  135. this.postData.flag = true;
  136. } else {
  137. this.postData.page++;
  138. // 延迟 200ms ,以保证设置窗口滚动已完成
  139. setTimeout(() => {
  140. this.postData.flag = true;
  141. }, 200)
  142. }
  143. })
  144. }
  145. get();
  146. },
  147. // 设置页面滚动位置
  148. setPageScrollTo(selector) {
  149. if (!selector) return;
  150. let view = uni.createSelectorQuery().in(this).select(selector);
  151. view.boundingClientRect((res) => {
  152. uni.pageScrollTo({
  153. scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度,示意上面还有信息。
  154. duration: 0
  155. });
  156. }).exec();
  157. },
  158. toggleTips(flag) {
  159. if (flag) {
  160. this.postData.loadText = '消息获取成功';
  161. setTimeout(() => {
  162. this.postData.loading = false;
  163. }, 300);
  164. } else {
  165. this.postData.loading = true;
  166. this.postData.loadText = '正在获取消息...';
  167. }
  168. },
  169. joinHistoryMsg() {
  170. return new Promise((done, fail) => {
  171. this.$chat.getHistoryMessageList(this.nextMessageId, this.userId, res => {
  172. this.nextMessageId = res.data.nextMessageId || 'null';
  173. done(!res.data ? [] : res.data.list);
  174. }, () => {
  175. done([]);
  176. });
  177. })
  178. },
  179. previewImage(url) {
  180. // 预览图片
  181. uni.previewImage({
  182. urls: [url]
  183. });
  184. },
  185. sendImage() {
  186. this.$chat.sendImage(this.userId, this.sendSuccess);
  187. },
  188. // 发送信息
  189. send() {
  190. if (!this.message) return this.$toast('内容不能为空');
  191. uni.showLoading();
  192. this.$chat.sendText(this.userId, this.message, this.sendSuccess);
  193. },
  194. sendSuccess(res) {
  195. this.chatList.push(res.data);
  196. this.message = '';
  197. uni.hideLoading();
  198. setTimeout(() => {
  199. uni.pageScrollTo({
  200. scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
  201. duration: 0
  202. });
  203. }, 200)
  204. }
  205. },
  206. }
  207. </script>
  208. <style lang="scss">
  209. .chat-box {
  210. .chat-tips {
  211. position: fixed;
  212. left: 0;
  213. top: 0;
  214. width: 100%;
  215. z-index: 9;
  216. background-color: $uni-primary;
  217. height: 72rpx;
  218. line-height: 72rpx;
  219. color: #fff;
  220. text-align: center;
  221. opacity: 0.9;
  222. }
  223. .chat-list {
  224. width: 100%;
  225. height: auto;
  226. padding-bottom: 120rpx;
  227. box-sizing: content-box;
  228. /* 兼容iPhoneX */
  229. margin-bottom: 0;
  230. margin-bottom: constant(safe-area-inset-bottom);
  231. margin-bottom: env(safe-area-inset-bottom);
  232. .chat-item {
  233. display: flex;
  234. padding: 20rpx;
  235. align-items: flex-start;
  236. align-content: flex-start;
  237. position: relative;
  238. .date {
  239. position: absolute;
  240. bottom: -5rpx;
  241. font-size: 20rpx;
  242. color: $uni-secondary-color;
  243. }
  244. .avatar {
  245. width: 80rpx;
  246. height: 80rpx;
  247. border-radius: 50%;
  248. border: #fff solid 1px;
  249. }
  250. .content-box {
  251. flex: 1;
  252. width: 0;
  253. display: flex;
  254. }
  255. .image-box {
  256. border-radius: 16rpx;
  257. padding-bottom: 4rpx;
  258. }
  259. .image-width {
  260. width: 280rpx;
  261. height: 200rpx;
  262. }
  263. .image-height {
  264. width: 200rpx;
  265. height: 280rpx;
  266. }
  267. .image-width-height {
  268. width: 200rpx;
  269. height: 200rpx;
  270. }
  271. .content {
  272. padding: 20rpx 30rpx;
  273. border-radius: 16rpx;
  274. word-break: break-all;
  275. line-height: 42rpx;
  276. position: relative;
  277. font-weight: 300;
  278. }
  279. /* 收到的消息 */
  280. &.pull {
  281. .content-box {
  282. margin-right: 100rpx;
  283. }
  284. .image-box {
  285. margin-left: 20rpx;
  286. }
  287. .content {
  288. margin-left: 20rpx;
  289. background-color: #fff;
  290. }
  291. .date {
  292. left: 124rpx;
  293. }
  294. }
  295. /* 发出的消息 */
  296. &.push {
  297. /* 主轴为水平方向,起点在右端。使不修改DOM结构,也能改变元素排列顺序 */
  298. flex-direction: row-reverse;
  299. .content-box {
  300. flex-direction: row-reverse;
  301. margin-left: 100rpx;
  302. }
  303. .image-box {
  304. margin-right: 20rpx;
  305. }
  306. .content {
  307. margin-right: 20rpx;
  308. background-color: $uni-primary;
  309. color: #fff;
  310. box-shadow: 0px 1px 12px rgba(3, 3, 3, 0.08);
  311. }
  312. .date {
  313. right: 124rpx;
  314. }
  315. }
  316. }
  317. }
  318. .chat-submit {
  319. position: fixed;
  320. left: 0;
  321. width: 100%;
  322. bottom: 0;
  323. height: 100rpx;
  324. z-index: 2;
  325. background-color: #fff;
  326. box-shadow: 0px 2px 10px rgba(3, 3, 3, 0.1);
  327. /* 兼容iPhoneX */
  328. padding-bottom: 0;
  329. padding-bottom: constant(safe-area-inset-bottom);
  330. padding-bottom: env(safe-area-inset-bottom);
  331. display: flex;
  332. align-items: center;
  333. .message-content {
  334. flex: 1;
  335. margin: 0 30rpx;
  336. border: 1px solid $uni-border-1;
  337. border-radius: 68rpx;
  338. height: 68rpx;
  339. padding: 0 20rpx;
  340. }
  341. .message-placeholder {
  342. color: #8c8c8c;
  343. font-weight: 300;
  344. }
  345. .send-button {
  346. width: 68rpx;
  347. height: 68rpx;
  348. border-radius: 50%;
  349. display: flex;
  350. align-items: center;
  351. justify-content: center;
  352. &.send-image {
  353. border: 1px solid $uni-border-1;
  354. margin-right: 20rpx;
  355. }
  356. &.send-submit {
  357. background: $uni-primary;
  358. margin-right: 30rpx;
  359. }
  360. }
  361. }
  362. }
  363. </style>