chat.vue 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. </view>
  17. </view>
  18. </view>
  19. <view class="chat-submit">
  20. <input type="text" class="message-content" v-model="message" placeholder="请输入聊天内容"
  21. placeholder-class="message-placeholder" :cursor-spacing="6" />
  22. <view class="send-image send-button" @tap="sendImage">
  23. <uni-icons type="images-filled" color="#8c8c8c" size="24"></uni-icons>
  24. </view>
  25. <view class="send-submit send-button" @tap="send">
  26. <uni-icons type="paperplane-filled" color="#fff" size="24"></uni-icons>
  27. </view>
  28. </view>
  29. </view>
  30. </template>
  31. <script>
  32. import {
  33. YeIMUniSDK,
  34. YeIMUniSDKDefines
  35. } from '@/uni_modules/wzJun1-YeIM-Uni-SDK/js_sdk/yeim-uni-sdk.min.js'
  36. import {
  37. login
  38. } from '@/request/api/chat.js'
  39. import md5 from '@/js_sdk/js-md5/build/md5.min.js';
  40. export default {
  41. data() {
  42. return {
  43. message: '',
  44. chatList: [],
  45. postData: {
  46. rows: 10, //每页数量
  47. page: 1, //页码
  48. flag: true, // 请求开关
  49. loading: true, // 加载中
  50. loadText: '正在获取消息...'
  51. },
  52. nextMessageId: '',
  53. nowUserId: ''
  54. }
  55. },
  56. onShow() {
  57. //监听新消息
  58. YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, this.onMessage);
  59. },
  60. onHide() {
  61. YeIMUniSDK.getInstance().removeEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, this.onMessage);
  62. },
  63. onLoad(body) {
  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. this.insertMessage(message);
  89. this.$chat.clearConversationUnread(this.userId);
  90. },
  91. insertMessage(message) {
  92. try {
  93. this.chatList.push(message);
  94. this.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. this.$chat.sendText(this.userId, this.message, this.sendSuccess);
  192. },
  193. sendSuccess(res) {
  194. this.chatList.push(res.data);
  195. this.message = '';
  196. setTimeout(() => {
  197. uni.pageScrollTo({
  198. scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
  199. duration: 0
  200. });
  201. }, 200)
  202. }
  203. },
  204. }
  205. </script>
  206. <style lang="scss">
  207. .chat-box {
  208. .chat-tips {
  209. position: fixed;
  210. left: 0;
  211. top: 0;
  212. width: 100%;
  213. z-index: 9;
  214. background-color: $uni-primary;
  215. height: 72rpx;
  216. line-height: 72rpx;
  217. color: #fff;
  218. text-align: center;
  219. opacity: 0.9;
  220. }
  221. .chat-list {
  222. width: 100%;
  223. height: auto;
  224. padding-bottom: 120rpx;
  225. box-sizing: content-box;
  226. /* 兼容iPhoneX */
  227. margin-bottom: 0;
  228. margin-bottom: constant(safe-area-inset-bottom);
  229. margin-bottom: env(safe-area-inset-bottom);
  230. .chat-item {
  231. display: flex;
  232. padding: 20rpx 20rpx 0 20rpx;
  233. align-items: flex-start;
  234. align-content: flex-start;
  235. .avatar {
  236. width: 80rpx;
  237. height: 80rpx;
  238. border-radius: 50%;
  239. border: #fff solid 1px;
  240. }
  241. .content-box {
  242. flex: 1;
  243. width: 0;
  244. display: flex;
  245. }
  246. .image-box {
  247. border-radius: 16rpx;
  248. }
  249. .image-width {
  250. width: 280rpx;
  251. height: 200rpx;
  252. }
  253. .image-height {
  254. width: 200rpx;
  255. height: 280rpx;
  256. }
  257. .image-width-height {
  258. width: 200rpx;
  259. height: 200rpx;
  260. }
  261. .content {
  262. padding: 20rpx 30rpx;
  263. border-radius: 16rpx;
  264. word-break: break-all;
  265. line-height: 42rpx;
  266. position: relative;
  267. font-weight: 300;
  268. }
  269. /* 收到的消息 */
  270. &.pull {
  271. .content-box {
  272. margin-right: 100rpx;
  273. }
  274. .image-box {
  275. margin-left: 20rpx;
  276. }
  277. .content {
  278. margin-left: 20rpx;
  279. background-color: #fff;
  280. }
  281. }
  282. /* 发出的消息 */
  283. &.push {
  284. /* 主轴为水平方向,起点在右端。使不修改DOM结构,也能改变元素排列顺序 */
  285. flex-direction: row-reverse;
  286. .content-box {
  287. flex-direction: row-reverse;
  288. margin-left: 100rpx;
  289. }
  290. .image-box {
  291. margin-right: 20rpx;
  292. }
  293. .content {
  294. margin-right: 20rpx;
  295. background-color: $uni-primary;
  296. color: #fff;
  297. box-shadow: 0px 1px 12px rgba(3, 3, 3, 0.08);
  298. }
  299. }
  300. }
  301. }
  302. .chat-submit {
  303. position: fixed;
  304. left: 0;
  305. width: 100%;
  306. bottom: 0;
  307. height: 100rpx;
  308. z-index: 2;
  309. background-color: #fff;
  310. box-shadow: 0px 2px 10px rgba(3, 3, 3, 0.1);
  311. /* 兼容iPhoneX */
  312. padding-bottom: 0;
  313. padding-bottom: constant(safe-area-inset-bottom);
  314. padding-bottom: env(safe-area-inset-bottom);
  315. display: flex;
  316. align-items: center;
  317. .message-content {
  318. flex: 1;
  319. margin: 0 30rpx;
  320. border: 1px solid $uni-border-1;
  321. border-radius: 68rpx;
  322. height: 68rpx;
  323. padding: 0 20rpx;
  324. }
  325. .message-placeholder {
  326. color: #8c8c8c;
  327. font-weight: 300;
  328. }
  329. .send-button {
  330. width: 68rpx;
  331. height: 68rpx;
  332. border-radius: 50%;
  333. display: flex;
  334. align-items: center;
  335. justify-content: center;
  336. &.send-image {
  337. border: 1px solid $uni-border-1;
  338. margin-right: 20rpx;
  339. }
  340. &.send-submit {
  341. background: $uni-primary;
  342. margin-right: 30rpx;
  343. }
  344. }
  345. }
  346. }
  347. </style>