uniapp页面回到顶部方法

本文讲的是在uniapp项目中实现页面回顶效果的方法。以下是代码(回顶可能多个页面都需要用到建议封装成一个组件)

一、方法一

<template>
    <view class="content">
        <view class="" v-for="(item,index) in 100" :key="index">
            {
    
    {index}}
        </view>
        <view class="upward" v-if="isShow" @click="Totop()">
            <u-icon name="arrow-upward" color="#434343" size="28"></u-icon>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                isShow:false,
            }
        },
        onPageScroll(e){
             // 监听页面滚动
            if(e.scrollTop>200){
                this.isShow=true;
            }else{
                this.isShow=false;
            }
        },
        methods: {
            Totop(){
                uni.pageScrollTo({
                    scrollTop: 0,//滚动到页面的目标位置
                    duration: 300
                });
            }
        }
    }
</script>

<style lang="less">
    .content{
        width: 100%;
        position: relative;
        .u-tabs{
            width: 100%;
            // margin: 18rpx auto;
            height: 80rpx;
            display: flex;
            align-items: center;
            background-color: #fff;
        }
        .upward{
            width: 70rpx;
            height: 70rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 100%;
            border: 3rpx solid #d0d0d0;
            margin-bottom: 20rpx;
            background-color: rgba(255, 255, 255, 0.4);
            position: fixed;
            bottom: 300rpx;
            right: 30rpx;
        }
    }
</style>

onPageScroll是页面生命周期,监听页面滚动,参数为Object

uni.pageScrollTo相关参数在官方文档可以查看

效果图(页面滚动距离大于200显示回顶按钮)

二、使用uView组件

<template>
    <view class="wrap">
        <text>滑动页面,返回顶部按钮将出现在右下角</text>
        <u-back-top :scroll-top="scrollTop"></u-back-top>
    </view>
</template>

<script>
export default {
    data() {
        return {
            scrollTop: 0
        }
    },
    onPageScroll(e) {
        this.scrollTop = e.scrollTop;
    }
};
</script>

<style lang="scss" scoped>
    .wrap {
        height: 200vh;
    }
</style>

猜你喜欢

转载自blog.csdn.net/topuu/article/details/129137930