uni模拟客服进行聊天

**

首先说一下思路:

需要用到websocket
作用:服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息
第一步:需要和websocket建立连接(由后端提供websocket服务器地址)
第二步:连接成功发送消息
第三步:收到消息并将消息渲染到页面
第四步:监听链接是否成功添加心跳
第五步:链接失败断开连接

**
**

原生的用法在浏览器里面是可以用的,但是打包成例如APP就必须要按照uni的写法来使用,简单举例 原生写法:
从商店进入聊天页面首先发一条商家信息,然后是文字发送

**

initwebsocket() {
				this.status = 'loading';
				//实例化websock
				this.websock = new WebSocket(path)//path是后端提供的
				//监听websock消息
				this.websock.onmessage = this.websocketonmessage
				//监听websock连接
				this.websock.onopen = this.websocketonopen
				//监听websock错误信息
				this.websock.onerror = this.websocketonerror
				//连接关闭
				this.websock.onclose = this.websocketclose
			},
			websocketsend(data) {
				console.log(data)
				console.log(this.websocket)
				if (this.websocket == undefined) {
					console.log(1)
					this.addMessage(data)
				}
				this.websock.send(data)
			},
			websocketonopen() {
				console.log('初始化成功')
				this.websocketsend(JSON.stringify({
					'uid': this.user_id,
					'type': 0
				}))
				uni.setNavigationBarTitle({
					title: this.shopname
				})
				this.load = false
				this.numconnect = 0;
				//心跳
				if (!this.heartbeat) {
					this.load = true
					this.heartbeat = setInterval(() => {
						this.websocketsend(JSON.stringify({
							'type': 'ping'
						}), 1)
					}, 1000 * 50);
				}
				if (this.fa == 1) { //首次进入先发送
					if (this.name != "") { //从商店进入发送商店信息
						this.sendsp()
					}
					this.fa = 2 //只发送一次
				}

			},
			websocketonmessage(e) {
				this.data = JSON.parse(e.data)
				//判断发送消息是接受者还是发送者且获取信息push新数组
				if (this.data.uid == this.user_id && this.data.to_uid == this.touid) {
					let resmsg = {
						isme: true,
						type: this.data.type,
						msg: this.data.msg
					}
					this.chatlist.push(resmsg)
				}
				if (this.data.uid == this.touid && this.data.to_uid == this.user_id) {
					let resmsg = {
						isme: false,
						type: this.data.type,
						msg: this.data.msg
					}
					this.chatlist.push(resmsg)
				}
				this.load = false;
				setTimeout(() => {
					uni.pageScrollTo({
						duration: 0,
						scrollTop: 999999 //滚动高度,单位px,这里也可用选择器属性:selector:选择器
					})
				}, 50)
			},
			websocketonerror() {
				this.initwebsocket()
			},
			websocketclose() {
				this.reconnectsys()
			},
			reconnectsys() {
				if (this.sysconnect > 0) {
					this.sysconnect--;
					this.numconnect++;
					this.load = true
					this.loadingText = '第' + this.numconnect + '次重连'
					setTimeout(() => {
						this.initwebsocket()
					}, 10000);
				} else {
					this.loadingText = '连接超时'
				}

			},
			//发送商店信息
			sendsp() {
				let messagedata = {
					uid: this.user_id,
					to_uid: this.touid,
					type: 6,
					msg: {
						"shopname": this.shopname, //对方聊天的名字
						"shopid": this.touid, //对方聊天的userID
						"shop_id": this.shop_id, //商店ID
						"name": this.name, //商店名称
						"photos": this.photos, //商店图片
						// "shopname": this.name, //对方聊天的名字
					}
				}
				this.websocketsend(JSON.stringify(messagedata))

			},
			//发送文字
			sendtext() {
				if (this.txt.trim() == "") { //清除空格且判断是否为空
					uni.showToast({
						title: "请输入内容",
						icon: "error",
						duration: 2000
					})
				} else {
					let messagedata = {
						uid: this.user_id,
						to_uid: this.touid,
						type: 1,
						msg: this.txt.trim()
					}
					this.websocketsend(JSON.stringify(messagedata))
					setTimeout(() => {
						uni.pageScrollTo({
							scrollTop: 999999,
							duration: 0, // 间隔时间
						})
					})
					this.txt = ""
				}

			},

**

uni写法,可查看uni官方文档

**

iniSys() {
				// 1.建立链接
				this.sys_info.socket = uni.connectSocket({
					url: this.sys_info.path,
					success: (e) => {
						console.log('链接建立成功', e)
					}
				});
				// 2.打开链接
				this.sys_info.socket.onOpen((e) => {
					console.log('链接建立')
					let obj = {
						uid: this.user_info.user_id,
						type: 0
					};
					// 建立映射关系
					this.sendMsg(JSON.stringify(obj));
					// 发送店铺或商品信息卡片
					if (!this.send_info.log) {
						// 为确保信息获取到,延迟发送
						this.sendShopOrGoods();
					}
				});
				// 3.监听错误
				this.sys_info.socket.onError((e) => {
					console.log('链接错误:', e.errMsg);
				});
				// 4.监听WebSocket接受到服务器的消息事件
				this.sys_info.socket.onMessage((e) => {
					let data = JSON.parse(e.data);
					console.log('接收到推送信息',data);
					if ((data.uid == this.user_info.user_id && data.to_uid ==this.to_info.to_uid) || (data.uid ==this.to_info.to_uid && data.to_uid == this.user_info.user_id)) {
						// 处理消息
						this.setMsg(data, 2);
						// 滚动到最底部
						this.setScroll();
					}
				});
				// 5.断线重连
				this.sys_info.socket.onClose((e) => {
					console.log('链接关闭:', e);
					this.reConnect();
				});
				// 6.心跳
				this.heartJump();
			},
			// socket重连
			reConnect() {
				if (this.sys_info.sysconnect > 0) {
					this.sys_info.sysconnect--;
					this.sys_info.numconnect++;
					console.log('第' + this.sys_info.numconnect + '次重连');
					setTimeout(() => {
						this.iniSys();
					}, 10000);
				} else {
					console.log('连接已超时');
				}
			},
			// 心跳
			heartJump() {
				if (!!!this.heartbeat) {
					this.heartbeat = setInterval(() => {
						this.sendMsg(JSON.stringify({
							type: 'ping'
						}))
					}, 1000 * 30)
				}
			},
			// 发送店铺/商品信息
			sendShopOrGoods() {
				if (this.send_info.type == 1) {
					// 发送店铺消息,且没有发送过消息
					let obj = {
						uid: this.user_info.user_id,
						to_uid: this.to_info.to_uid,
						type: 6,
						msg: {
							page_title: this.shop_info.shop_name,
							shop_id: this.shop_info.shop_id,
							name: this.shop_info.shop_name,
							photos: this.shop_info.shop_photo
						}
					};
					this.sendMsg(JSON.stringify(obj));
					this.send_info.log = true;
				}
				if (this.send_info.type == 2) {
					// 发送商品信息
					let obj = {
						uid: this.user_info.user_id,
						to_uid: this.to_info.to_uid,
						type: 5,
						msg: {
							page_title: this.shop_info.shop_name,
							shop_id: this.shop_info.shop_id,
							goods_id: this.goods_info.goods_id,
							title: this.goods_info.goods_name,
							photo: this.goods_info.goods_photo,
							price: this.goods_info.price
						}
					};
					this.sendMsg(JSON.stringify(obj))
					this.send_info.log = true;
				}
			},
			sendMsg(data) {
				if (!!this.sys_info.socket) {
					// 发送消息
					this.sys_info.socket.send({
						data: data,
						success: (e) => {
							console.log('消息推送成功',data)
						},
						fail: (e) => {
							console.log("消息推送失败",data)
						}
					})
				} else {
					// 调接口发送消息
					this.addMsg(data);
				}
			},
			setMsg(data, from = 1) {
				// 处理接受到的消息:from[1聊天记录消息;2推送消息]
				console.log(from==1 ? '处理接收到的信息' : '发送的信息',data)
				console.log('处理消息-发送人信息',this.user_info)
				console.log('处理消息-接收人信息',this.to_info)
				let obj = {};
				obj.type = data.type;
				if(from == 1){
					if (data.user_id == this.user_info.user_id) {
						obj.isme = true;
						obj.nickname = this.user_info.nickname;
						obj.face = this.user_info.face;
					} else {
						obj.isme = false;
						obj.nickname = this.to_info.to_nickname;
						obj.face = this.to_info.to_face;
					}
				}
				if(from == 2){
					if (data.uid == this.user_info.user_id) {
						obj.isme = true;
						obj.nickname = this.user_info.nickname;
						obj.face = this.user_info.face;
					} else {
						obj.isme = false;
						obj.nickname = this.to_info.to_nickname;
						obj.face = this.to_info.to_face;
					}
				}

				if (data.type == 1) {
					// 文字消息
					obj.msg = data.msg;
				}
				if (data.type == 2) {
					// 图片消息
					obj.img_url = data.msg;
				}
				// 音频消息
				// if(data.type == 3){}
				// 文件消息
				// if(data.type == 4){}
				if (data.type == 5) {
					// 商品消息
					obj.goods_id = data.msg.goods_id;
					obj.goods_img = data.msg.photo;
					obj.goods_title = data.msg.title;
					obj.goods_price = data.msg.price;
				}
				if (data.type == 6) {
					// 店铺消息
					obj.shop_id = data.msg.shop_id;
					obj.shop_img = data.msg.photos;
					obj.shop_name = data.msg.name;
				}
				if (from == 1) {
					// 聊天记录往前插入
					this.chatlist.unshift(obj);
				}
				if (from == 2) {
					// 推送消息往后插入
					this.chatlist.push(obj);
				}
			},
			//点击发送按钮
			sendText() {
				if (this.txt.trim() == "") { //清除空格且判断是否为空
					uni.showToast({
						title: "请输入内容",
						icon: "error",
						duration: 1000
					})
				} else {
					let obj = {
						uid: this.user_info.user_id,
						to_uid: this.to_info.to_uid,
						type: 1,
						msg: this.txt.trim()
					}
					this.sendMsg(JSON.stringify(obj));
					this.txt = "";
				}
			},

**

因为uni打包其他不可以直接用原生,所以比较推荐用uni写法,最后附上全部代码

**

<template>
	<view style="height: auto !important;">
		<view class="chat-body">
			<u-loadmore :status="page_info.status" :loadingText="page_info.loadingText" v-show="page_info.load" />
			<view v-for="(item,index) in chatlist" :key="index">
				<view class="chat-one" v-if="!item.isme">
					<image :src="item.face" mode="" />
					<view class="chat-box">
						<view class="chat-sender" style="width: 70px;">
							{{item.nickname}}
						</view>
						<view class="chat-content" v-if="item.type == 1">
							{{item.msg}}
						</view>
						<view class="chat-img" v-if="item.type == 2">
							<image :src="item.img_url" mode="widthFix" />
						</view>
						<view class="chat-goos" v-if="item.type == 5" @click="goodsid(item.goods_id)">
							<view class="left">
								<image :src="item.goods_img" mode=""></image>
							</view>
							<view class="right">
								<text>{{item.goods_title}}</text><br>
								<text style="font-size: 13px;">{{item.goods_price}}</text>
							</view>
						</view>
						<view class="chat-goos" v-if="item.type == 6" @click="spid(item.shop_id)">
							<view class="left">
								<image :src="item.shop_img" mode=""></image>
							</view>
							<view class="right">
								<text>{{item.shop_name}}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="chat-one" style="text-align: right;" v-if="item.isme">
					<view class="chat-box">
						<view class="chat-sender" style="display: inline-block;text-align: right;" v-if="item.isme">
							{{item.nickname}}
						</view>
						<view class="chat-content" v-if="item.type == 1">
							{{item.msg}}
						</view>
						<view class="chat-img" v-if="item.type == 2">
							<image :src="item.img_url" mode="widthFix" />
						</view>
						<view class="chat-goos" v-if="item.type == 5" @click="goodsid(item.goods_id)">
							<view class="left">
								<image :src="item.goods_img" mode=""></image>
							</view>
							<view class="right">
								<text>{{item.goods_title}}</text><br>
								<text style="font-size: 13px;">{{item.goods_price}}</text>
							</view>
						</view>
						<view class="chat-goos" v-if="item.type == 6" @click="spid(item.shop_id)">
							<view class="left">
								<image :src="item.shop_img" mode=""></image>
							</view>
							<view class="right">
								<text>{{item.shop_name}}</text>
							</view>
						</view>
					</view>
					<image :src="item.face" mode="" />
				</view>
			</view>
			<view class="send">
				<input type="text" value="" placeholder="请输入聊天内容" v-model="txt" />
				<image src="../../static/xiangce.png" @click="sendImg"></image>
				<button type="default" @click="sendText">发送</button>
			</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				chatlist: [], //聊天记录
				txt: "", //发送消息
				send_info: {
					type: 0, //0进入页面不发送消息;1发送店家信息;2发送商品信息
					log: false, //true有发送记录;false没有发送记录
				},
				user_info: { //发送消息用户信息
					user_id: uni.getStorageSync("user_id"), //发送消息人uid
					nickname: uni.getStorageSync("nickname"), //发送消息人昵称
					face: uni.getStorageSync("myphoto") //发送消息人头像
				},
				to_info: { //接收消息用户信息
					to_uid: '', //接收消息人uid
					to_nickname: '', //接收消息人昵称
					to_face: '' //接收消息人头像
				},
				shop_info: { //店铺信息
					shop_id: '', //店铺shop_id
					shop_name: '', //店铺名称
					shop_photo: '' //店铺图片
				},
				goods_info: { //商品信息
					goods_id: '', //商品goods_id
					goods_name: '', //商品名称
					goods_photo: '', //商品图片
					price: '', //商品价格易货额
					xj: '' //商品现金
				},
				sys_info: { //websocket配置参数
					path: 'wss://chart.zhilongyihuo.com/wss', //websocket服务器地址
					socket: null, //websocket对象
					sysconnect: 3, //断线重连次数
					numconnect: 0, //重连计数
					heartbeat: null, //心跳对象
				},
				page_info: { //页面配置参数
					load: false, //聊天顶部提示信息控制开关
					loadingText: '正在连接', //聊天顶部提示信息
					status: 'loadmore', //loadmore:加载更多,loading:正在加载,nomore:加载完毕,没有了
					pageindex: 1, //分页当前页码
					count: 0, //聊天记录总数
					nums: 0, //已经获取到的聊天记录数目
				}
			}
		},
		onLoad(options) {
			// 设置配置参数
			this.setConfig(options);
			// 确保用户信息存在
			if (!!!this.user_info.user_id) {
				this.isLogin();
				return;
			}
			// 向上解决问题:把问题解决在源头
			// 获取聊天记录
			setTimeout(()=>{
				this.getchatlist();
			},300)
			// // 链接socket
			setTimeout(()=>{
				this.iniSys();
			},800)
		},
		destroyed() {
			// 生命周期结束关闭socket链接
			uni.closeSocket()
		},
		onShow() {},
		onPullDownRefresh() {
			if (this.page_info.nums < this.page_info.count) {
				this.page_info.status = 'loading';
				this.page_info.pageindex++;
				this.getchatlist();
				console.log("下拉翻页");
			}
		},
		methods: {
			setConfig(options) {
				if (!!options.user_id) {
					// 发送人user_id
					this.user_info.user_id = options.user_id;
					this.getUserInfo(this.user_info.user_id);
				}
				if (!!options.to_user_id) {
					// 接收人user_id
					this.to_info.to_uid = options.to_user_id;
					this.getUserInfo(this.to_info.to_uid, 2)
				}
				if (!!options.shop_id) {
					// 点击店铺进入页面
					this.getShopInfo(options.shop_id);
					this.send_info.type = 1;
				}
				if (!!options.goods_id) {
					// 点击商品进入页面
					this.getGoodsInfo(options.goods_id);
					this.send_info.type = 2;
				}
			},
			// 获取用户信息
			async getUserInfo(user_id, type = 1) {
				const res = await this.$myrequest({
					url: '/app/user/getUserInfo',
					method: 'POST',
					data: {
						user_id: user_id,
					},
				});
				if (res.data.code == 1) {
					let obj = res.data.data;
					if (type == 1) {
						// 发送人信息
						this.user_info.nickname = obj.nickname;
						this.user_info.face = obj.face;
					}
					if (type == 2) {
						// 接收人信息
						this.to_info.to_nickname = obj.nickname;
						this.to_info.to_face = obj.face;
						uni.setNavigationBarTitle({
							'title': obj.shop_name
						})
					}
				}
			},
			// 获取商店信息
			async getShopInfo(shop_id) {
				const res = await this.$myrequest({
					url: '/app/shop/details',
					method: 'POST',
					data: {
						shop_id: shop_id,
					},
				});
				if (res.data.code == 1) {
					let obj = res.data.data;
					this.shop_info.shop_id = obj.shop_id;
					this.shop_info.shop_name = obj.shop_name;
					this.shop_info.shop_photo = obj.photo;
				}
			},
			// 获取商品信息
			async getGoodsInfo(goods_id) {
				const res = await this.$myrequest({
					url: '/app/goods/details',
					method: 'POST',
					data: {
						goods_id: goods_id,
					},
				})
				if (res.data.code == 1) {
					let obj = res.data.data;
					this.shop_info.shop_id = obj.shop_id;
					this.shop_info.shop_name = obj.shop.shop_name;
					this.shop_info.shop_photo = obj.shop.photo;
					this.goods_info.goods_id = obj.goods_id;
					this.goods_info.goods_name = obj.title;
					this.goods_info.goods_photo = obj.photo;
					this.goods_info.price = obj.price;
					this.goods_info.xj = obj.xj;
				}
			},
			// 登录
			isLogin() {
				uni.showModal({
					content: '请先登录',
					success: (e) => {
						if (e.confirm) {
							// 点击确定按钮,跳转登录
							uni.navigateTo({
								url: "/pages/my/login"
							})
						}
						if (e.cancel) {
							// 点击取消按钮,返回上一页
							uni.navigateBack()
						}
					}
				})
				return;
			},
			// 让页面滚动到最底部
			setScroll() {
				setTimeout(() => {
					uni.pageScrollTo({
						duration: 0,
						scrollTop: 999999 //滚动高度,单位px,这里也可用选择器属性:selector:选择器
					})
				}, 50)
			},
			iniSys() {
				// 1.建立链接
				this.sys_info.socket = uni.connectSocket({
					url: this.sys_info.path,
					success: (e) => {
						console.log('链接建立成功', e)
					}
				});
				// 2.打开链接
				this.sys_info.socket.onOpen((e) => {
					console.log('链接建立')
					let obj = {
						uid: this.user_info.user_id,
						type: 0
					};
					// 建立映射关系
					this.sendMsg(JSON.stringify(obj));
					// 发送店铺或商品信息卡片
					if (!this.send_info.log) {
						// 为确保信息获取到,延迟发送
						this.sendShopOrGoods();
					}
				});
				// 3.监听错误
				this.sys_info.socket.onError((e) => {
					console.log('链接错误:', e.errMsg);
				});
				// 4.监听WebSocket接受到服务器的消息事件
				this.sys_info.socket.onMessage((e) => {
					let data = JSON.parse(e.data);
					console.log('接收到推送信息',data);
					if ((data.uid == this.user_info.user_id && data.to_uid == this.to_info.to_uid) || (data.uid ==
							this.to_info.to_uid && data.to_uid == this.user_info.user_id)) {
						// 处理消息
						this.setMsg(data, 2);
						// 滚动到最底部
						this.setScroll();
					}
				});
				// 5.断线重连
				this.sys_info.socket.onClose((e) => {
					console.log('链接关闭:', e);
					this.reConnect();
				});
				// 6.心跳
				this.heartJump();
			},
			// socket重连
			reConnect() {
				if (this.sys_info.sysconnect > 0) {
					this.sys_info.sysconnect--;
					this.sys_info.numconnect++;
					console.log('第' + this.sys_info.numconnect + '次重连');
					setTimeout(() => {
						this.iniSys();
					}, 10000);
				} else {
					console.log('连接已超时');
				}
			},
			// 心跳
			heartJump() {
				if (!!!this.heartbeat) {
					this.heartbeat = setInterval(() => {
						this.sendMsg(JSON.stringify({
							type: 'ping'
						}))
					}, 1000 * 30)
				}
			},
			// 发送店铺/商品信息
			sendShopOrGoods() {
				if (this.send_info.type == 1) {
					// 发送店铺消息,且没有发送过消息
					let obj = {
						uid: this.user_info.user_id,
						to_uid: this.to_info.to_uid,
						type: 6,
						msg: {
							page_title: this.shop_info.shop_name,
							shop_id: this.shop_info.shop_id,
							name: this.shop_info.shop_name,
							photos: this.shop_info.shop_photo
						}
					};
					this.sendMsg(JSON.stringify(obj));
					this.send_info.log = true;
				}
				if (this.send_info.type == 2) {
					// 发送商品信息
					let obj = {
						uid: this.user_info.user_id,
						to_uid: this.to_info.to_uid,
						type: 5,
						msg: {
							page_title: this.shop_info.shop_name,
							shop_id: this.shop_info.shop_id,
							goods_id: this.goods_info.goods_id,
							title: this.goods_info.goods_name,
							photo: this.goods_info.goods_photo,
							price: this.goods_info.price
						}
					};
					this.sendMsg(JSON.stringify(obj))
					this.send_info.log = true;
				}
			},
			sendMsg(data) {
				if (!!this.sys_info.socket) {
					// 发送消息
					this.sys_info.socket.send({
						data: data,
						success: (e) => {
							console.log('消息推送成功',data)
						},
						fail: (e) => {
							console.log("消息推送失败",data)
						}
					})
				} else {
					// 调接口发送消息
					this.addMsg(data);
				}
			},
			setMsg(data, from = 1) {
				// 处理接受到的消息:from[1聊天记录消息;2推送消息]
				console.log(from==1 ? '处理接收到的信息' : '发送的信息',data)
				console.log('处理消息-发送人信息',this.user_info)
				console.log('处理消息-接收人信息',this.to_info)
				let obj = {};
				obj.type = data.type;
				if(from == 1){
					if (data.user_id == this.user_info.user_id) {
						obj.isme = true;
						obj.nickname = this.user_info.nickname;
						obj.face = this.user_info.face;
					} else {
						obj.isme = false;
						obj.nickname = this.to_info.to_nickname;
						obj.face = this.to_info.to_face;
					}
				}
				if(from == 2){
					if (data.uid == this.user_info.user_id) {
						obj.isme = true;
						obj.nickname = this.user_info.nickname;
						obj.face = this.user_info.face;
					} else {
						obj.isme = false;
						obj.nickname = this.to_info.to_nickname;
						obj.face = this.to_info.to_face;
					}
				}

				if (data.type == 1) {
					// 文字消息
					obj.msg = data.msg;
				}
				if (data.type == 2) {
					// 图片消息
					obj.img_url = data.msg;
				}
				// 音频消息
				// if(data.type == 3){}
				// 文件消息
				// if(data.type == 4){}
				if (data.type == 5) {
					// 商品消息
					obj.goods_id = data.msg.goods_id;
					obj.goods_img = data.msg.photo;
					obj.goods_title = data.msg.title;
					obj.goods_price = data.msg.price;
				}
				if (data.type == 6) {
					// 店铺消息
					obj.shop_id = data.msg.shop_id;
					obj.shop_img = data.msg.photos;
					obj.shop_name = data.msg.name;
				}
				if (from == 1) {
					// 聊天记录往前插入
					this.chatlist.unshift(obj);
				}
				if (from == 2) {
					// 推送消息往后插入
					this.chatlist.push(obj);
				}
			},
			// 获取聊天记录
			async getchatlist() {
				this.status = 'loading';
				const res = await this.$myrequest({
					url: '/app/chat/lists?page=' + this.page_info.pageindex,
					method: 'POST',
					header: {
						'token': uni.getStorageSync("token"), //自定义请求头信息
					},
					data: {
						user_id: this.user_info.user_id,
						to_user_id: this.to_info.to_uid
					}
				});
				if (res.data.code == 1) {
					// 聊天记录总数
					this.page_info.count = res.data.data.count;
					// 已获取的聊天记录数目
					this.page_info.nums += res.data.data.list.length;
					if (res.data.data.count < 20) {
						// 加载下一页,<20条没有更多
						this.status = 'nomore';
					}
					if (res.data.data.list.length > 0) {
						res.data.data.list.forEach((e) => {
							this.setMsg(e);
						})
					}
					if (this.page_info.pageindex == 1) {
						// 渲染第一页聊天记录后,定位到页面最底部
						this.setScroll()
					}
				} else {
					this.status = "nomore"
					uni.showToast({
						title: res.data.msg,
						icon: "error",
						duration: 1000
					})
				}
			},
			//点击发送按钮
			sendText() {
				if (this.txt.trim() == "") { //清除空格且判断是否为空
					uni.showToast({
						title: "请输入内容",
						icon: "error",
						duration: 1000
					})
				} else {
					let obj = {
						uid: this.user_info.user_id,
						to_uid: this.to_info.to_uid,
						type: 1,
						msg: this.txt.trim()
					}
					this.sendMsg(JSON.stringify(obj));
					this.txt = "";
				}
			},
			//发送图片
			sendImg() {
				uni.chooseImage({
					count: 1, //选择图片张数
					sizeType: ['original', 'compressed'], //类型:压缩或者原图
					sourceType: ['album', 'camera'], //来源:相册或相机
					success: res => {
						this.uploadFilePromise(res.tempFilePaths[0])
						this.$nextTick(() => {
							uni.pageScrollTo({
								scrollTop: 99999,
								duration: 0
							})
						})
					}
				})
			},
			//上传图片
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://www.zhilongyihuo.com/index.php?s=/app/upload/uploadVideo', // 仅为示例,非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							console.log(res.data)
							let obj = {
								uid: this.user_info.user_id,
								to_uid: this.to_info.to_uid,
								type: 2,
								msg: "https://www.zhilongyihuo.com/attachs/" + res.data
							}
							this.sendMsg(JSON.stringify(obj))
						}
					});
				})
			},

			// 发送聊天
			async addMsg(obj) {
				const res = await this.$myrequest({
					url: '/app/chat/addMessage',
					method: 'POST',
					header: {
						'token': uni.getStorageSync("token"), //自定义请求头信息
					},
					data: {
						msg: obj
					}
				});
				if (res.data.code == 1) {
					// 发送成功
					let e = JSON.parse(obj);
					if (e.type != 0 && e.type != 'ping') {
						// 处理消息
						await this.setMsg(e, 2);
						// 滚动到最底部
						this.setScroll();
					}
				} else {
					// 发送失败
					uni.showToast({
						title: res.data.msg,
						icon: "error",
						duration: 1000
					})
				}
			},

			//商品跳转信息
			goodsid(id) {
				uni.navigateTo({
					url: "/pages/goos_detail/goos_detail?id=" + id
				})
			},
			//商店跳转信息
			spid(id) {
				uni.navigateTo({
					url: "/pages/shop_detail/shop_detail?id=" + id
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.chat-body {
		width: 100%;
		background: #e1e1e1;
		top: 0px;
		padding-bottom: 70px;
		position: absolute;

		.chat-one {
			padding: 1%;

			image {
				width: 40px;
				height: 40px;
				border-radius: 50%;
				display: inline-block;
				vertical-align: top
			}

			.chat-box {
				display: inline-block;
				vertical-align: sub;

				.chat-sender {
					width: 70px;
					background: #dadada;
					color: #888;
				}

				.chat-content {
					background: white;
					padding: 1%;
					border-radius: 5px;
					max-width: 300px;
					text-align: left;
				}

				.chat-goos {
					background: white;
					border-radius: 5px;
					max-width: 300px;
					display: flex;

					.left {
						display: inline-block;

						image {
							width: 100px;
							margin: 5px;
						}
					}

					.right {
						display: flex;
						flex-direction: column;
						justify-content: center;
						margin-right: 10px;
					}
				}

				image {
					border-radius: 0px;
					height: 88px;
					width: 200px;
				}
			}
		}

		.send {
			width: 96%;
			background: #d1d1d1;
			padding: 2%;
			position: fixed;
			bottom: 0;
			z-index: 9;

			input {
				width: 65%;
				height: 40px;
				display: inline-block;
				border-radius: 15px;
				background: white;
				padding-left: 3%;
			}

			image {
				width: 40px;
				height: 40px;
				margin-left: 5px;
			}

			button {
				display: inline-block;
				margin-left: 3%;
				height: 40px;
				background: #368fec;
				color: white;
				line-height: 40px;
				font-size: 15px;
			}
		}
	}
</style>

完结,撒花~欢迎大佬指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值