chat.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 == 'whx' ? '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. }
  54. },
  55. onShow() {
  56. //监听新消息
  57. YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, this.onMessage);
  58. },
  59. onHide() {
  60. YeIMUniSDK.getInstance().removeEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, this.onMessage);
  61. },
  62. onLoad() {
  63. let userId = 'whx';
  64. //模拟计算sign,换取登陆Token,此处建议在各个系统的服务端进行。
  65. let timestamp = (new Date()).getTime() + 86400 * 1000 * 1000; //1天后过期
  66. let sign = md5(userId + timestamp + "50abd47112ebe8c5a73f4694c96a49ce");
  67. login({
  68. userId: userId,
  69. timestamp: timestamp,
  70. sign: sign
  71. }).then(res => {
  72. if (res.code === 200) {
  73. let token = res.data.token;
  74. YeIMUniSDK.getInstance().connect({
  75. userId: userId,
  76. token: token,
  77. success: (response) => {
  78. if (response.code === 200) {
  79. this.getHistoryMsg();
  80. }
  81. },
  82. fail: (err) => {
  83. console.log(err);
  84. }
  85. });
  86. }
  87. })
  88. },
  89. onPageScroll(e) {
  90. if (e.scrollTop < 5) {
  91. this.getHistoryMsg();
  92. }
  93. },
  94. methods: {
  95. returnImageClass(item) {
  96. let w = item.thumbnailWidth,
  97. h = item.thumbnailHeight;
  98. let str = ''
  99. if (w > h) str = 'image-width';
  100. if (w == h) str = 'image-width-height';
  101. if (w < h) str = 'image-height';
  102. return str + ' image-box';
  103. },
  104. onMessage(e) {
  105. let message = e;
  106. this.insertMessage(message);
  107. },
  108. insertMessage(message) {
  109. try {
  110. this.chatList.push(message);
  111. this.message = '';
  112. setTimeout(() => {
  113. uni.pageScrollTo({
  114. scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
  115. duration: 0
  116. });
  117. }, 200)
  118. } catch (e) {
  119. console.log(e)
  120. }
  121. },
  122. getHistoryMsg() {
  123. if (!this.postData.flag) {
  124. return; //
  125. }
  126. // 此处用到 ES7 的 async/await 知识,为使代码更加优美。不懂的请自行学习。
  127. let get = async () => {
  128. this.toggleTips();
  129. this.postData.flag = false;
  130. let data = await this.joinHistoryMsg();
  131. // 获取待滚动元素选择器,解决插入数据后,滚动条定位时使用
  132. let selector = '';
  133. if (this.postData.page > 1) {
  134. // 非第一页,则取历史消息数据的第一条信息元素
  135. selector = `#msg-${this.chatList[0].time}`;
  136. } else {
  137. // 第一页,则取当前消息数据的最后一条信息元素
  138. selector = `#msg-${data[data.length-1].time}`;
  139. }
  140. // 将获取到的消息数据合并到消息数组中
  141. this.chatList = [...data, ...this.chatList];
  142. // 数据挂载后执行,不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
  143. this.$nextTick(() => {
  144. // 设置当前滚动的位置
  145. this.setPageScrollTo(selector);
  146. this.toggleTips(true);
  147. if (data.length < this.postData.rows) {
  148. // 当前消息数据条数小于请求要求条数时,则无更多消息,不再允许请求。
  149. // 可在此处编写无更多消息数据时的逻辑
  150. } else {
  151. this.postData.page++;
  152. // 延迟 200ms ,以保证设置窗口滚动已完成
  153. setTimeout(() => {
  154. this.postData.flag = true;
  155. }, 200)
  156. }
  157. })
  158. }
  159. get();
  160. },
  161. // 设置页面滚动位置
  162. setPageScrollTo(selector) {
  163. let view = uni.createSelectorQuery().in(this).select(selector);
  164. view.boundingClientRect((res) => {
  165. uni.pageScrollTo({
  166. scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度,示意上面还有信息。
  167. duration: 0
  168. });
  169. }).exec();
  170. },
  171. toggleTips(flag) {
  172. if (flag) {
  173. this.postData.loadText = '消息获取成功';
  174. setTimeout(() => {
  175. this.postData.loading = false;
  176. }, 300);
  177. } else {
  178. this.postData.loading = true;
  179. this.postData.loadText = '正在获取消息...';
  180. }
  181. },
  182. joinHistoryMsg() {
  183. // 此处用到 ES6 的 Promise 知识,不懂的请自行学习。
  184. return new Promise((done, fail) => {
  185. YeIMUniSDK.getInstance().getHistoryMessageList({
  186. nextMessageId: this.nextMessageId,
  187. conversationId: "dcs",
  188. success: (res) => {
  189. this.nextMessageId = res.data.nextMessageId
  190. done(res.data.list);
  191. console.log(res.data);
  192. },
  193. fail: (err) => {
  194. console.log(err)
  195. }
  196. });
  197. })
  198. },
  199. previewImage(url) {
  200. // 预览图片
  201. uni.previewImage({
  202. urls: [url]
  203. });
  204. },
  205. sendImage() {
  206. uni.chooseImage({
  207. count: 1, //默认9
  208. sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  209. sourceType: ['album'], //从相册选择
  210. success: res => {
  211. uni.getImageInfo({
  212. src: res.tempFilePaths[0],
  213. success: image => {
  214. //创建图片消息
  215. let message = YeIMUniSDK.getInstance().createImageMessage({
  216. toId: 'dcs', //接收者用户ID字符串
  217. conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE
  218. .PRIVATE, //会话类型:私聊
  219. body: {
  220. file: {
  221. tempFilePath: res.tempFilePaths[0], //本地图片临时路径
  222. width: image.width, //图片宽度
  223. height: image.height //图片高度
  224. }
  225. },
  226. extra: "这是拓展的自定义的内容",
  227. onProgress: (progress) => {
  228. console.log('上传进度' + progress.progress);
  229. console.log('已经上传的数据长度' + progress
  230. .totalBytesSent);
  231. console.log('预期需要上传的数据总长度' + progress
  232. .totalBytesExpectedToSend);
  233. }
  234. });
  235. //发送消息
  236. YeIMUniSDK.getInstance().sendMessage({
  237. message: message,
  238. success: (res) => {
  239. this.chatList.push(res.data);
  240. this.message = '';
  241. setTimeout(() => {
  242. uni.pageScrollTo({
  243. scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
  244. duration: 0
  245. });
  246. console.log(9999);
  247. }, 200)
  248. },
  249. fail: (err) => {
  250. console.log(err)
  251. }
  252. });
  253. }
  254. });
  255. }
  256. });
  257. },
  258. // 发送信息
  259. send() {
  260. if (!this.message) return this.$toast('内容不能为空');
  261. //创建文字消息
  262. let message = YeIMUniSDK.getInstance().createTextMessage({
  263. toId: 'dcs', //接收者用户ID字符串
  264. conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE.PRIVATE, //会话类型:私聊
  265. body: {
  266. text: this.message //文本消息内容字符串
  267. },
  268. extra: ""
  269. });
  270. //发送消息
  271. YeIMUniSDK.getInstance().sendMessage({
  272. message: message,
  273. success: (res) => {
  274. this.chatList.push(res.data);
  275. this.message = '';
  276. setTimeout(() => {
  277. uni.pageScrollTo({
  278. scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
  279. duration: 0
  280. });
  281. console.log(9999);
  282. }, 200)
  283. },
  284. fail: (err) => {
  285. console.log(err)
  286. }
  287. });
  288. }
  289. },
  290. }
  291. </script>
  292. <style lang="scss">
  293. .chat-box {
  294. .chat-tips {
  295. position: fixed;
  296. left: 0;
  297. top: 0;
  298. width: 100%;
  299. z-index: 9;
  300. background-color: $uni-primary;
  301. height: 72rpx;
  302. line-height: 72rpx;
  303. color: #fff;
  304. text-align: center;
  305. opacity: 0.9;
  306. }
  307. .chat-list {
  308. width: 100%;
  309. height: auto;
  310. padding-bottom: 120rpx;
  311. box-sizing: content-box;
  312. /* 兼容iPhoneX */
  313. margin-bottom: 0;
  314. margin-bottom: constant(safe-area-inset-bottom);
  315. margin-bottom: env(safe-area-inset-bottom);
  316. .chat-item {
  317. display: flex;
  318. padding: 20rpx 20rpx 0 20rpx;
  319. align-items: flex-start;
  320. align-content: flex-start;
  321. .avatar {
  322. width: 80rpx;
  323. height: 80rpx;
  324. border-radius: 50%;
  325. border: #fff solid 1px;
  326. }
  327. .content-box {
  328. flex: 1;
  329. width: 0;
  330. display: flex;
  331. }
  332. .image-box {
  333. border-radius: 16rpx;
  334. }
  335. .image-width {
  336. width: 280rpx;
  337. height: 200rpx;
  338. }
  339. .image-height {
  340. width: 200rpx;
  341. height: 280rpx;
  342. }
  343. .image-width-height {
  344. width: 200rpx;
  345. height: 200rpx;
  346. }
  347. .content {
  348. padding: 20rpx 30rpx;
  349. border-radius: 16rpx;
  350. word-break: break-all;
  351. line-height: 42rpx;
  352. position: relative;
  353. font-weight: 300;
  354. }
  355. /* 收到的消息 */
  356. &.pull {
  357. .content-box {
  358. margin-right: 100rpx;
  359. }
  360. .image-box {
  361. margin-left: 20rpx;
  362. }
  363. .content {
  364. margin-left: 20rpx;
  365. background-color: #fff;
  366. }
  367. }
  368. /* 发出的消息 */
  369. &.push {
  370. /* 主轴为水平方向,起点在右端。使不修改DOM结构,也能改变元素排列顺序 */
  371. flex-direction: row-reverse;
  372. .content-box {
  373. flex-direction: row-reverse;
  374. margin-left: 100rpx;
  375. }
  376. .image-box {
  377. margin-right: 20rpx;
  378. }
  379. .content {
  380. margin-right: 20rpx;
  381. background-color: $uni-primary;
  382. color: #fff;
  383. box-shadow: 0px 1px 12px rgba(3, 3, 3, 0.08);
  384. }
  385. }
  386. }
  387. }
  388. .chat-submit {
  389. position: fixed;
  390. left: 0;
  391. width: 100%;
  392. bottom: 0;
  393. height: 100rpx;
  394. z-index: 2;
  395. background-color: #fff;
  396. box-shadow: 0px 2px 10px rgba(3, 3, 3, 0.1);
  397. /* 兼容iPhoneX */
  398. padding-bottom: 0;
  399. padding-bottom: constant(safe-area-inset-bottom);
  400. padding-bottom: env(safe-area-inset-bottom);
  401. display: flex;
  402. align-items: center;
  403. .message-content {
  404. flex: 1;
  405. margin: 0 30rpx;
  406. border: 1px solid $uni-border-1;
  407. border-radius: 68rpx;
  408. height: 68rpx;
  409. padding: 0 20rpx;
  410. }
  411. .message-placeholder {
  412. color: #8c8c8c;
  413. font-weight: 300;
  414. }
  415. .send-button {
  416. width: 68rpx;
  417. height: 68rpx;
  418. border-radius: 50%;
  419. display: flex;
  420. align-items: center;
  421. justify-content: center;
  422. &.send-image {
  423. border: 1px solid $uni-border-1;
  424. margin-right: 20rpx;
  425. }
  426. &.send-submit {
  427. background: $uni-primary;
  428. margin-right: 30rpx;
  429. }
  430. }
  431. }
  432. }
  433. </style>