今天有小伙伴问我,制作(IM)聊天时,发送的聊天消息不能自动滚动,通过一些了算法,随后发现有一些问题,不是很好,问我有没有相关的好的方法。嗯嗯嗯,当然,我这确实有一个比较好的方法。具体如下
原理 利用 scroll-view的scroll-into-view属性
效果图 见附件
具体代码如下
<template>
<view class='test'>
<scroll-view :scroll-into-view="viewIndex" scroll-view scroll-with-animation='true' :style="{'box-sizing':'border-box', 'padding':'20rpx','height':'200rpx'}"
scroll-y="true" class="scroll-Y">
<!-- 具体聊天内容 -->
<view v-for="(c,i) in chatList" :key="i">
{{c}}
</view>
<!-- 可滚动到底部的view标签 -->
<view :id="'im_'+chatList.length" class="bottom"></view>
</scroll-view>
<view>
<button @click="add">添加一行内容</button>
</view>
</view>
</template>
<!-- 页面方法 -->
<script>
export default {
data() {
return {
viewIndex: '',
chatList: ['你好', '很好'], // 模拟消息记录 为演示滚动效果,此处只有简单的消息信息
}
},
methods: {
add() {
//模拟发消息添加一条记录
this.chatList[this.chatList.length] = "你添加了一行内容" + this.chatList.length;
this.viewIndex = "";
//设置viewIndex值,使聊天滚动到底部
this.$nextTick(() => {
this.viewIndex = "im_" + this.chatList.length;
})
}
},
}
</script>
<style scoped>
.bottom {
width: 100vw;
height: 20rpx;
}
</style>