【uni-app】uni-app实现聊天页面功能——功能篇(下)

前言

前面我有写关于如何进行聊天页面布局和实现聊天消息滚动到最底部的文章。

【uni-app】uni-app实现聊天页面功能——功能篇(上)

【uni-app】uni-app实现聊天页面功能(小程序)——布局篇

这篇文章是基于这两篇的基础上完善的。

主要还是实现以下两个功能:

  1. 点击聊天框的时候,聊天框随键盘抬起且聊天消息列表滚动到最底部,但整体页面不抬起

  2. 聊天框textarea根据内容自适应高度,且聊天消息列表随着聊天框的增高而滚动到最底部(说白了就是最底部的消息不会被增高的聊天框给挡住)

在这里插入图片描述

一、聊天框随键盘抬起

uni-app官方文档中其实有给出关于这个的解决方案,只用设置一个属性。

扫描二维码关注公众号,回复: 15290828 查看本文章

textarea | uni-app官网 (dcloud.net.cn)

textarea的属性:

adjust-position —— 键盘抬起时,是否自动上推页面(默认值为true)

cursor-spacing —— 指定光标与键盘的距离,单位px(就是设置键盘与输入框的距离,默认值为0)

<textarea cursor-spacing = "60"></textarea>

虽然这种方法简单,但是有一个不好的地方是:页面整体会上移

在这里插入图片描述

如果想让聊天框随键盘抬起的同时不想让页面上移,可以参考下面这个方法。

思路

首先我们需要在键盘抬起的时候获取到键盘的高度,然后给聊天框动态设置合适的bottom值(键盘的高度),最后给textarea的属性adjust-position设置为false。

至于在点击聊天框的时候聊天消息定位到最底部(不会被遮挡)我将放到第二个板块去讲!!!


获取键盘高度采用官方给出的api(最快且稳定的)实现:uni.hideKeyboard() | uni-app官网 (dcloud.net.cn)

我们在页面加载时设置uni.onKeyboardHeightChange监听事件去获取到键盘高度,在页面卸载时使用uni.offKeyboardHeightChange解除监听键盘高度事件。

代码实现

视图部分(简写):

<template>
	<view class="chat">
		<scroll-view :style="{height: `${windowHeight-keyboardHeight}rpx`}"
		id="scrollview"
		scroll-y="true" 
		:scroll-top="scrollTop"
		:scroll-with-animation="true"
		class="scroll-view"
		>
			<view id="msglistview" class="chat-body">
				...
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<view class="chat-bottom">
			<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
				<view class="uni-textarea">
					<textarea v-model="chatMsg"
					  maxlength="300"
					  confirm-type="send"
                      :adjust-position="false"
                      :show-confirm-bar="false"
					  auto-height ></textarea>
				</view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>

js部分:

data(){
    
    
    return{
    
    
        //键盘高度
        keyboardHeight:0,
        // 聊天框距离底部的高度
        bottomHeight: 0,
    }
},	
onLoad(){
    
    
	uni.onKeyboardHeightChange(res => {
    
    
        //这里正常来讲代码直接写
        //this.keyboardHeight=this.rpxTopx(res.height)就行了
        //但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
		this.keyboardHeight = this.rpxTopx(res.height-60)
		if(this.keyboardHeight<0)this.keyboardHeight = 0;
	})
},
onUnload(){
    
    
	uni.offKeyboardHeightChange()//如果不传入监听的对象,则移除所有监听函数
}

二、聊天消息列表随着聊天框的增高而滚动到最底部

需求:

点击聊天框,聊天消息定位到最底部。聊天框textarea根据内容自适应高度(已实现),且聊天消息列表随着聊天框的增高而滚动到最底部(说白了就是最底部的消息不会被增高的聊天框给挡住)

思路

因为点击聊天框的时候,键盘抬起,所以此时的内容可视区高度应该是:屏幕高度-(聊天框高度+键盘高度),所以将这个高度赋值给聊天滚动区,同时页面更新时再调用聊天滚动到底部的函数就实现了

聊天框的高度我们可以用boundingClientRect获取到,然后在textarea的行数发生变化的时候(@linechange)调用获取聊天框高度的函数。

还有个小细节就是,套在聊天框最外层的view也要跟随着聊天框改高度,然后颜色也要设置成跟界面背景色一样,这样当聊天框弹起来的时候就不会闪出一个白板。

三、问题

设置scroll-view中的scroll-with-animation为true时,聊天发送消息会有一个过渡的动画效果。由于有动画时长,消息的发送会有一定的延时,这个动画的时长比我们设置的消息滚动到底部scrollToBottom函数的延时要长(也就是说,动画还未完成,就执行滚动到底部的函数,这只是我的个人猜想)。这样会导致发送的聊天消息比较长时(聊天消息只有一行的时候没影响),发送出去的消息会有一个回弹,页面不能滚到最底部(不能完整显示出聊天消息)。
在这里插入图片描述

解决方案
把动画效果删了,不加scroll-with-animation
(如果有更好的解决办法也可以告诉我!)

完整代码实现

整个页面完整代码:

<template>
	<view class="chat">
		<scroll-view  :style="{height: `${windowHeight-inputHeight}rpx`}"
		id="scrollview"
		scroll-y="true" 
		:scroll-top="scrollTop"
		class="scroll-view"
		>
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.userContent != ''" >
						<!-- 文字内容 -->
						<view class="content right">
						{
   
   {item.userContent}}
						</view>
						<!-- 头像 -->
						<view class="avatar">
						</view>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-if="item.botContent != ''">
						<!-- 头像 -->     
						<view class="avatar">
						</view>
						<!-- 文字内容 -->
						<view class="content left">
							{
   
   {item.botContent}}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位,防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
                <view class="uni-textarea">
					<textarea v-model="chatMsg"
					  maxlength="300"
					  confirm-type="send"
					  @confirm="handleSend"
					  :show-confirm-bar="false"
					  :adjust-position="false"
					  @linechange="sendHeight"
					  @focus="focus" @blur="blur"
					 auto-height></textarea>
				</view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
      
      
		data() {
      
      
			return {
      
      
				//键盘高度
				keyboardHeight:0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId:'',
				//发送的消息
				chatMsg:"",
				msgList:[
					{
      
      
					    botContent: "hello,请问我有什么可以帮助你的吗?",
					    recordId: 0,
					    titleId: 0,
					    userContent: "",
					    userId: 0
					},
					{
      
      
					    botContent: "",
					    recordId: 0,
					    titleId: 0,
					    userContent: "你好呀我想问你一件事",
					    userId: 0
					},
				]	
			}
		},
		updated(){
      
      
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
      
      
			windowHeight() {
      
      
			    return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight(){
      
      
				return this.bottomHeight+this.keyboardHeight
			}
		},
		onLoad(){
      
      
			uni.onKeyboardHeightChange(res => {
      
      
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height-30)
				if(this.keyboardHeight<0)this.keyboardHeight = 0;
			})
		},
		onUnload(){
      
      
			uni.offKeyboardHeightChange()
		},
		methods: {
      
      
			focus(){
      
      
				this.scrollToBottom()
			},
			blur(){
      
      
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px){
      
      
				let deviceWidth = wx.getSystemInfoSync().windowWidth
				let rpx = ( 750 / deviceWidth ) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight(){
      
      
				setTimeout(()=>{
      
      
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res =>{
      
      
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				},10)
			},
			// 滚动至聊天底部
			scrollToBottom(e){
      
      
				setTimeout(()=>{
      
      
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) =>{
      
      
						if(res[1].height > res[0].height){
      
      
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				},15)
			},
			// 发送消息
			handleSend() {
      
      
				//如果消息不为空
				if(!this.chatMsg||!/^\s+$/.test(this.chatMsg)){
      
      
					let obj = {
      
      
						botContent: "",
						recordId: 0,
						titleId: 0,
						userContent: this.chatMsg,
						userId: 0
					}
					this.msgList.push(obj);
					this.chatMsg = '';
					this.scrollToBottom()
				}else {
      
      
					this.$modal.showToast('不能发送空白消息')
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;
	
	view,button,text,input,textarea {
      
      
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {
      
      
		.scroll-view {
      
      
			::-webkit-scrollbar {
      
      
					    display: none;
					    width: 0 !important;
					    height: 0 !important;
					    -webkit-appearance: none;
					    background: transparent;
					    color: transparent;
					  }
			
			// background-color: orange;
			background-color: #F6F6F6;
			
			.chat-body {
      
      
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;
				
				.self {
      
      
					justify-content: flex-end;
				}
				.item {
      
      
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
      
      
						background-color: $chatContentbgc;
					}
					.left {
      
      
						background-color: #FFFFFF;
					}
                    // 聊天消息的三角形
					.right::after {
      
      
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
      
      
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
      
      
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
      
      
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 8rpx;
						overflow: hidden;
						
						image {
      
      
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
      
      
			width: 100%;
			height: 177rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;
			

			.send-msg {
      
      
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #EDEDED;
				transition: all 0.1s ease;
			}

			.uni-textarea {
      
      
				padding-bottom: 70rpx;
                
				textarea {
      
      
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 43rpx;
					padding: 5rpx 8rpx;
				}
			}
            
			.send-btn {
      
      
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				background: $sendBtnbgc;
				border-radius: 8rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
	}
</style>

总结

聊天界面差不多就这样完结了!很多功能都是边做边想到的,主要是实现更好的交互体验!有问题欢迎来评论区留言噢~

猜你喜欢

转载自blog.csdn.net/qq_51250105/article/details/130221088