uniapp page back to the top method

This article is about the method of realizing the page back effect in the uniapp project. The following is the code (return to the top may need to be used for multiple pages, it is recommended to encapsulate it into a component)

1. Method 1

<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 is the page life cycle, monitors page scrolling, and the parameter is Object

uni.pageScrollTo related parameters can be viewed in the official document

Effect picture (the page scrolling distance is greater than 200 and the back button is displayed)

2. Use the uView component

<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>

Guess you like

Origin blog.csdn.net/topuu/article/details/129137930
Recommended