123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458 |
- <template>
- <view class="chat-box">
- <view class="chat-tips" v-if="postData.loading">
- {{postData.loadText}}
- </view>
- <view class="chat-list">
- <view :id="`msg-${item.time}`" v-for="(item,index) in chatList" :key="index">
- <view class="chat-item" :class=" item.from == 'whx' ? 'push':'pull' ">
- <image :src="item.fromUserInfo.avatarUrl" mode="aspectFill" class="avatar"></image>
- <view class="content-box">
- <view class="content" v-if="item.type === 'text'">{{item.body.text}}</view>
- <image :src="item.body.thumbnailUrl" mode="aspectFill"
- @tap="previewImage(item.body.originalUrl)" :class="[returnImageClass(item.body)]" v-else>
- </image>
- </view>
- </view>
- </view>
- </view>
- <view class="chat-submit">
- <input type="text" class="message-content" v-model="message" placeholder="请输入聊天内容"
- placeholder-class="message-placeholder" :cursor-spacing="6" />
- <view class="send-image send-button" @tap="sendImage">
- <uni-icons type="images-filled" color="#8c8c8c" size="24"></uni-icons>
- </view>
- <view class="send-submit send-button" @tap="send">
- <uni-icons type="paperplane-filled" color="#fff" size="24"></uni-icons>
- </view>
- </view>
- </view>
- </template>
- <script>
- import {
- YeIMUniSDK,
- YeIMUniSDKDefines
- } from '@/uni_modules/wzJun1-YeIM-Uni-SDK/js_sdk/yeim-uni-sdk.min.js'
- import {
- login
- } from '@/request/api/chat.js'
- import md5 from '@/js_sdk/js-md5/build/md5.min.js';
- export default {
- data() {
- return {
- message: '',
- chatList: [],
- postData: {
- rows: 10, //每页数量
- page: 1, //页码
- flag: true, // 请求开关
- loading: true, // 加载中
- loadText: '正在获取消息...'
- },
- nextMessageId: ''
- }
- },
- onShow() {
- //监听新消息
- YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, this.onMessage);
- },
- onHide() {
- YeIMUniSDK.getInstance().removeEventListener(YeIMUniSDKDefines.EVENT.MESSAGE_RECEIVED, this.onMessage);
- },
- onLoad() {
- let userId = 'whx';
- //模拟计算sign,换取登陆Token,此处建议在各个系统的服务端进行。
- let timestamp = (new Date()).getTime() + 86400 * 1000 * 1000; //1天后过期
- let sign = md5(userId + timestamp + "50abd47112ebe8c5a73f4694c96a49ce");
- login({
- userId: userId,
- timestamp: timestamp,
- sign: sign
- }).then(res => {
- if (res.code === 200) {
- let token = res.data.token;
- YeIMUniSDK.getInstance().connect({
- userId: userId,
- token: token,
- success: (response) => {
- if (response.code === 200) {
- this.getHistoryMsg();
- }
- },
- fail: (err) => {
- console.log(err);
- }
- });
- }
- })
- },
- onPageScroll(e) {
- if (e.scrollTop < 5) {
- this.getHistoryMsg();
- }
- },
- methods: {
- returnImageClass(item) {
- let w = item.thumbnailWidth,
- h = item.thumbnailHeight;
- let str = ''
- if (w > h) str = 'image-width';
- if (w == h) str = 'image-width-height';
- if (w < h) str = 'image-height';
- return str + ' image-box';
- },
- onMessage(e) {
- let message = e;
- this.insertMessage(message);
- },
- insertMessage(message) {
- try {
- this.chatList.push(message);
- this.message = '';
- setTimeout(() => {
- uni.pageScrollTo({
- scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
- duration: 0
- });
- }, 200)
- } catch (e) {
- console.log(e)
- }
- },
- getHistoryMsg() {
- if (!this.postData.flag) {
- return; //
- }
- // 此处用到 ES7 的 async/await 知识,为使代码更加优美。不懂的请自行学习。
- let get = async () => {
- this.toggleTips();
- this.postData.flag = false;
- let data = await this.joinHistoryMsg();
- // 获取待滚动元素选择器,解决插入数据后,滚动条定位时使用
- let selector = '';
- if (this.postData.page > 1) {
- // 非第一页,则取历史消息数据的第一条信息元素
- selector = `#msg-${this.chatList[0].time}`;
- } else {
- // 第一页,则取当前消息数据的最后一条信息元素
- selector = `#msg-${data[data.length-1].time}`;
- }
- // 将获取到的消息数据合并到消息数组中
- this.chatList = [...data, ...this.chatList];
- // 数据挂载后执行,不懂的请自行阅读 Vue.js 文档对 Vue.nextTick 函数说明。
- this.$nextTick(() => {
- // 设置当前滚动的位置
- this.setPageScrollTo(selector);
- this.toggleTips(true);
- if (data.length < this.postData.rows) {
- // 当前消息数据条数小于请求要求条数时,则无更多消息,不再允许请求。
- // 可在此处编写无更多消息数据时的逻辑
- } else {
- this.postData.page++;
- // 延迟 200ms ,以保证设置窗口滚动已完成
- setTimeout(() => {
- this.postData.flag = true;
- }, 200)
- }
- })
- }
- get();
- },
- // 设置页面滚动位置
- setPageScrollTo(selector) {
- let view = uni.createSelectorQuery().in(this).select(selector);
- view.boundingClientRect((res) => {
- uni.pageScrollTo({
- scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度,示意上面还有信息。
- duration: 0
- });
- }).exec();
- },
- toggleTips(flag) {
- if (flag) {
- this.postData.loadText = '消息获取成功';
- setTimeout(() => {
- this.postData.loading = false;
- }, 300);
- } else {
- this.postData.loading = true;
- this.postData.loadText = '正在获取消息...';
- }
- },
- joinHistoryMsg() {
- // 此处用到 ES6 的 Promise 知识,不懂的请自行学习。
- return new Promise((done, fail) => {
- YeIMUniSDK.getInstance().getHistoryMessageList({
- nextMessageId: this.nextMessageId,
- conversationId: "dcs",
- success: (res) => {
- this.nextMessageId = res.data.nextMessageId
- done(res.data.list);
- console.log(res.data);
- },
- fail: (err) => {
- console.log(err)
- }
- });
- })
- },
- previewImage(url) {
- // 预览图片
- uni.previewImage({
- urls: [url]
- });
- },
- sendImage() {
- uni.chooseImage({
- count: 1, //默认9
- sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
- sourceType: ['album'], //从相册选择
- success: res => {
- uni.getImageInfo({
- src: res.tempFilePaths[0],
- success: image => {
- //创建图片消息
- let message = YeIMUniSDK.getInstance().createImageMessage({
- toId: 'dcs', //接收者用户ID字符串
- conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE
- .PRIVATE, //会话类型:私聊
- body: {
- file: {
- tempFilePath: res.tempFilePaths[0], //本地图片临时路径
- width: image.width, //图片宽度
- height: image.height //图片高度
- }
- },
- extra: "这是拓展的自定义的内容",
- onProgress: (progress) => {
- console.log('上传进度' + progress.progress);
- console.log('已经上传的数据长度' + progress
- .totalBytesSent);
- console.log('预期需要上传的数据总长度' + progress
- .totalBytesExpectedToSend);
- }
- });
- //发送消息
- YeIMUniSDK.getInstance().sendMessage({
- message: message,
- success: (res) => {
- this.chatList.push(res.data);
- this.message = '';
- setTimeout(() => {
- uni.pageScrollTo({
- scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
- duration: 0
- });
- console.log(9999);
- }, 200)
- },
- fail: (err) => {
- console.log(err)
- }
- });
- }
- });
- }
- });
- },
- // 发送信息
- send() {
- if (!this.message) return this.$toast('内容不能为空');
- //创建文字消息
- let message = YeIMUniSDK.getInstance().createTextMessage({
- toId: 'dcs', //接收者用户ID字符串
- conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE.PRIVATE, //会话类型:私聊
- body: {
- text: this.message //文本消息内容字符串
- },
- extra: ""
- });
- //发送消息
- YeIMUniSDK.getInstance().sendMessage({
- message: message,
- success: (res) => {
- this.chatList.push(res.data);
- this.message = '';
- setTimeout(() => {
- uni.pageScrollTo({
- scrollTop: 99999999, // -30 为多显示出大半个消息的高度,示意上面还有信息。
- duration: 0
- });
- console.log(9999);
- }, 200)
- },
- fail: (err) => {
- console.log(err)
- }
- });
- }
- },
- }
- </script>
- <style lang="scss">
- .chat-box {
- .chat-tips {
- position: fixed;
- left: 0;
- top: 0;
- width: 100%;
- z-index: 9;
- background-color: $uni-primary;
- height: 72rpx;
- line-height: 72rpx;
- color: #fff;
- text-align: center;
- opacity: 0.9;
- }
- .chat-list {
- width: 100%;
- height: auto;
- padding-bottom: 120rpx;
- box-sizing: content-box;
- /* 兼容iPhoneX */
- margin-bottom: 0;
- margin-bottom: constant(safe-area-inset-bottom);
- margin-bottom: env(safe-area-inset-bottom);
- .chat-item {
- display: flex;
- padding: 20rpx 20rpx 0 20rpx;
- align-items: flex-start;
- align-content: flex-start;
- .avatar {
- width: 80rpx;
- height: 80rpx;
- border-radius: 50%;
- border: #fff solid 1px;
- }
- .content-box {
- flex: 1;
- width: 0;
- display: flex;
- }
- .image-box {
- border-radius: 16rpx;
- }
- .image-width {
- width: 280rpx;
- height: 200rpx;
- }
- .image-height {
- width: 200rpx;
- height: 280rpx;
- }
- .image-width-height {
- width: 200rpx;
- height: 200rpx;
- }
- .content {
- padding: 20rpx 30rpx;
- border-radius: 16rpx;
- word-break: break-all;
- line-height: 42rpx;
- position: relative;
- font-weight: 300;
- }
- /* 收到的消息 */
- &.pull {
- .content-box {
- margin-right: 100rpx;
- }
- .image-box {
- margin-left: 20rpx;
- }
- .content {
- margin-left: 20rpx;
- background-color: #fff;
- }
- }
- /* 发出的消息 */
- &.push {
- /* 主轴为水平方向,起点在右端。使不修改DOM结构,也能改变元素排列顺序 */
- flex-direction: row-reverse;
- .content-box {
- flex-direction: row-reverse;
- margin-left: 100rpx;
- }
- .image-box {
- margin-right: 20rpx;
- }
- .content {
- margin-right: 20rpx;
- background-color: $uni-primary;
- color: #fff;
- box-shadow: 0px 1px 12px rgba(3, 3, 3, 0.08);
- }
- }
- }
- }
- .chat-submit {
- position: fixed;
- left: 0;
- width: 100%;
- bottom: 0;
- height: 100rpx;
- z-index: 2;
- background-color: #fff;
- box-shadow: 0px 2px 10px rgba(3, 3, 3, 0.1);
- /* 兼容iPhoneX */
- padding-bottom: 0;
- padding-bottom: constant(safe-area-inset-bottom);
- padding-bottom: env(safe-area-inset-bottom);
- display: flex;
- align-items: center;
- .message-content {
- flex: 1;
- margin: 0 30rpx;
- border: 1px solid $uni-border-1;
- border-radius: 68rpx;
- height: 68rpx;
- padding: 0 20rpx;
- }
- .message-placeholder {
- color: #8c8c8c;
- font-weight: 300;
- }
- .send-button {
- width: 68rpx;
- height: 68rpx;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- &.send-image {
- border: 1px solid $uni-border-1;
- margin-right: 20rpx;
- }
- &.send-submit {
- background: $uni-primary;
- margin-right: 30rpx;
- }
- }
- }
- }
- </style>
|