uni-app nvue 使用list cell keep-scroll-position无效

uni-app nvue 使用list cell keep-scroll-position无效

开发环境 版本号 项目创建方式
Windows win10 HBuilderX

产品分类:uniapp/App

PC开发环境操作系统:Windows

HBuilderX类型:正式

HBuilderX版本号:3.98

手机系统:Android

手机系统版本号:Android 10

手机厂商:OPPO

手机机型:PADM00

页面类型:vue

vue版本:vue2

打包方式:云端

操作步骤:

<template>
<view class="content">
<list :pagingEnabled="true">
<cell v-for="item in list"  :keep-scroll-position="item == 5">
<view class="box" :style="{height}">
<text class="box-text">{{item}}{{item == 5}}</text>
</view>
</cell>
</list>
</view>
</template> 
<script>
export default {
data() {
return {
list:[],
}
},
computed:{
height(){
return uni.getSystemInfoSync().windowHeight + 'px'
}
},
onLoad() {
setTimeout(()=>{
this.list.push(...[5,6])
this.$nextTick(()=>{
this.flag = true
setTimeout(()=>{
this.list.unshift(...[1,2,3,4])
},2000)
}),1000)
}
}
}
</script>  
<style lang="scss" scoped>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 750rpx;
flex: 1;
.box{
width: 750rpx;
background:#efefef;
align-items: center;
justify-content: center;
.box-text{
color: #111;
font-size: 40rpx;
}
}
}
</style>

更多关于uni-app nvue 使用list cell keep-scroll-position无效的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app nvue 使用list cell keep-scroll-position无效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uni-app 中,nvue 页面使用的是 weex 的原生渲染引擎,因此在处理滚动位置时,可能会遇到一些与 vue 页面不同的行为。关于 list 组件中的 keep-scroll-position 属性无效的问题,以下是一些可能的原因和解决方案:

1. keep-scroll-position 的作用

keep-scroll-positionlist 组件的一个属性,用于在列表数据更新时保持当前的滚动位置。默认情况下,当列表数据发生变化时,列表会重新渲染并滚动到顶部。设置 keep-scroll-positiontrue 可以避免这种行为。

2. 可能的原因

  • nvue 的渲染机制nvue 使用的是原生渲染,与 vue 页面的 Web 渲染机制不同,可能会导致某些属性的行为不一致。
  • list 组件的实现list 组件在 nvue 中的实现可能与 vue 页面中的实现不同,导致 keep-scroll-position 属性无效。
  • 数据更新方式:如果列表数据是通过直接替换整个数组的方式更新的,可能会导致 keep-scroll-position 失效。

3. 解决方案

3.1 检查 list 组件的使用

确保 list 组件的使用方式正确,并且 keep-scroll-position 属性被正确设置:

<list :keep-scroll-position="true">
  <cell v-for="item in items" :key="item.id">
    <!-- 内容 -->
  </cell>
</list>

3.2 使用 scrollTo 方法手动控制滚动位置

如果 keep-scroll-position 无效,可以尝试在数据更新后,手动调用 scrollTo 方法来保持滚动位置。

// 假设你有一个 ref 引用到 list 组件
this.$refs.list.scrollTo({
  x: 0,
  y: currentScrollPosition, // 你需要记录当前的滚动位置
  animated: false
});

3.3 使用 scroll-view 替代 list

如果 list 组件的 keep-scroll-position 无效,可以考虑使用 scroll-view 组件来替代 list,并手动控制滚动位置。

<scroll-view :scroll-y="true" :scroll-top="scrollTop">
  <view v-for="item in items" :key="item.id">
    <!-- 内容 -->
  </view>
</scroll-view>

在数据更新时,手动记录并设置 scrollTop 的值:

data() {
  return {
    scrollTop: 0
  };
},
methods: {
  updateItems() {
    // 记录当前的滚动位置
    this.scrollTop = this.$refs.scrollView.scrollTop;
    
    // 更新数据
    this.items = newItems;
    
    // 恢复滚动位置
    this.$nextTick(() => {
      this.scrollTop = this.scrollTop;
    });
  }
}
回到顶部