uniapp中scroll-view滚动到指定组件位置
最近做一个uniapp的聊天室界面,当获取聊天信息之后需要下滑到底部最新消息处,当上拉刷新的时候需要再往上一格移动到下面的消息
通过scroll-view的滚动和下拉刷新来实现
在scroll-view的属性中设置 :scroll-into-view="state.scrollIntoMessageId"
通过动态设置scrollIntoMessageId来到指定的组件位置
记住这个id是给组件的 id
属性赋值之后才行,不是 key
我开始也以为是key,实际不是。比如下面这个代码循环创建一个列表的view,并且每个赋值一个单独的messageId给他的id属性,那么要滚动到哪里就在scrollIntoMessageId设置为哪个的值就行
<view v-for="message in state.dataList" :key="message.messageId" :id="message.messageId">
// 消息列表
<scroll-view
scroll-y
:refresher-triggered="state.isRefreshing"
refresher-enabled
style="height: 60vh"
:scroll-into-view="state.scrollIntoMessageId"
@refresherrefresh="handleRefresh"
@refresherpulling="handlePulling"
@scrolltoupper="handleScrolltoupper">
<view class="message-list">
<view v-for="message in state.dataList" :key="message.messageId" :id="message.messageId">
<view v-if="message.userId === userStore.userWsid" class="message-line">
<!--自己的消息-->
<view class="message-line__self">
<view class="message-line__self-content" v-if="message.content && message.content.length">
<view class="message-content-text">{{ message.content }}</view>
</view>
<view class="message-line-attach-self-files" v-if="message.attachFiles && message.attachFiles.length"></view>
</view>
<view class="message-avatar">
<image src="@/static/images/navigation-page/ic_doctor.png" />
</view>
</view>
<view v-else class="message-line">
<view class="message-avatar">
<image src="@/static/images/navigation-page/ic_doctor.png" />
</view>
<!--对方信息-->
<view class="message-line__other">
<view class="message-line__other-content" v-if="message.content && message.content.length">
<view class="message-content-text">{{ message.content }}</view>
</view>
</view>
</view>
</view>
</view>
<view id="message-bottom"></view>
</scroll-view>
// 获取消息
const getMessageList = (page: number) => {
setTimeout(() => {
let newDataList = new Array<Message>()
for (let i = 1; i < 10; i++) {
let scrollId = "s_" + page + "_" + i
newDataList.push({ userId: userStore.userWsid, content: "测试消息" + scrollId, sendTime: "", attachFiles: [""], messageId: scrollId })
}
if (page > 1) {
state.topMessageId = newDataList[newDataList.length - 1].messageId
}
state.dataList = newDataList.concat(state.dataList)
uni.stopPullDownRefresh()
state.isRefreshing = false
scrollToMessage()
}, 1000)
}
// 设置滚动
const scrollToMessage = () => {
nextTick(() => {
if (state.currentPage === 1) {
// 第一页的消息
state.scrollIntoMessageId = state.dataList[state.dataList.length - 1].messageId
} else {
state.scrollIntoMessageId = state.topMessageId
}
})
}
// 对话信息
interface Message {
userId: string, // 讲话人的id
content: string,
sendTime: string,
attachFiles: string[],
messageId: string
}