使用scroll-top使聊天对话滚动到底部
scroll-view需要设置高度
输入内容后,必然要在对话界面的底部显示内容,但是在uni-app下不知道如何能操作DOM来显示和定位,有说需要通过uni.pageScrollTo的方式,但是这个页面刷新的太厉害,输入框都刷新了,没法使用。所以只能使用scroll-view组件。但是通过scroll-view使用竖向滚动时,需要给 <scroll-view> 一个固定高度。为了适配屏幕的大小,则需要通过计算来确定scroll-view的高度。
<scroll-view id="scrollview" class="chat-window" scroll-y="true" :style="{height: style.contentViewHeight + 'px'}" :scroll-with-animation="true" :scroll-top="scrollTop">
<block v-for="chat in chatList">
<online-chat-control :chatItem="chat"></online-chat-control>
</block>
</scroll-view>
js代码
data() {
return {
// 聊天页面时时滚动样式
style: {
pageHeight: 0,
contentViewHeight: 0,
footViewHeight: 90,
mitemHeight: 0,
},
scrollTop : 0
}
},
created() {
const res = uni.getSystemInfoSync(); //获取手机可使用窗口高度 api为获取系统信息同步接口
this.style.pageHeight = res.windowHeight;
this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (300); //像素 因为给出的是像素高度 然后我们用的是upx 所以换算一下
},
onLoad() {
this.scrollToBottom(); //创建后调用回到底部方法
}
发送消息时调用
/**
* @information 跳转页面底部
*/
scrollToBottom() {
let that = this;
let query = uni.createSelectorQuery();
query.selectAll('.cu-chat').boundingClientRect();
query.select('#scrollview').boundingClientRect();
query.exec((res) => {
hat.style.mitemHeight = 0;
res[0].forEach((rect) => that.style.mitemHeight = that.style.mitemHeight + rect.height + 40) //获取所有内部子元素的高度
// 因为vue的虚拟DOM 每次生成的新消息都是之前的,所以采用异步setTimeout 主要就是添加了这定时器
setTimeout(() => {
if (that.style.mitemHeight > (that.style.contentViewHeight - 100)) { //判断子元素高度是否大于显示高度
that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight //用子元素的高度减去显示的高度就获益获得序言滚动的高度
}
}, 100)
})
},