因为做移动端,有个表格数据要动态写成html格式进行拼接,所以用scroll视图来做的,做分页功能的时候遇到了问题,就是切换页面的时候发现只有第一次点击才能返回到顶部,其他时候都没效果。必须在onScroll里面不停的更改this.pageData.scrollTop。
这是由于vue和小程序的视图层同步方式不同导致的。解决方式可参考如下代码:
<template>
<view>
<page-head :title="title"></page-head>
<view class="page-body">
<view class="page-section">
<view class="page-section-title">
<text>Vertical Scroll\n纵向滚动</text>
</view>
<view class="page-section-spacing">
<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower"
@scroll="scroll">
<view id="demo1" class="scroll-view-item color1">A</view>
<view id="demo2" class="scroll-view-item color2">B</view>
<view id="demo3" class="scroll-view-item color3">C</view>
</scroll-view>
</view>
<view class="btn-area">
<button @tap="goTop" class="page-body-button" type="default">返回顶部</button>
</view>
</view>
<view class="page-section">
<view class="page-section-title">
<text>Horizontal Scroll\n横向滚动</text>
</view>
<view class="page-section-spacing">
<scroll-view class="scroll-view_H" scroll-x="true" @scroll="scroll">
<view id="demo1" class="scroll-view-item_H color1">A</view>
<view id="demo2" class="scroll-view-item_H color2">B</view>
<view id="demo3" class="scroll-view-item_H color3">C</view>
</scroll-view>
</view>
</view>
</view>
</view>
</template>
export default {
data() {
return {
title: 'scroll-view',
scrollTop: 0,
old: {
scrollTop: 0
}
}
},
methods: {
upper: function(e) {
console.log(e)
},
lower: function(e) {
console.log(e)
},
scroll: function(e) {
console.log(e)
this.old.scrollTop = e.detail.scrollTop
},
goTop: function(e) {
// 解决view层不同步的问题
this.scrollTop = this.old.scrollTop
this.$nextTick(function() {
this.scrollTop = 0
})
}
}
}
给滚动绑定一个变量,初始值为0;再设置一个一样的变量。当点击时,用old变量去给scrollTop重新赋值;再调用$nextTick等dom结构生成后,再重新赋值scrolltop,就能回到顶部了。