vue中使用better-scroll封裝scroll組件


<template>
    <!-- 封裝滾動組件 -->
    <div class="wrapper" ref="swiper">
        <!-- wrapper里面只能放一個元素,就是滾動的 -->
        <div class="content">
            <slot></slot>
        </div>
    </div>
</template>

<script>
import BScroll from "better-scroll";
export default {
    name: "Scroll",
    props: {
        probeType: {
            type: Number,
            default() {
                //默認是0, 不監聽滾動
                return 0;
            }
        }
    },
    data() {
        return {
            scroll: null
        };
    },
    mounted() {
        this.scroll = new BScroll(this.$refs.swiper, {
            click: true,
            probeType: this.probeType
        });
        //監聽滾動的位置;
        this.scroll.on("scroll", position => {
            console.log(position);
            this.$emit("scroll", position);
        });
        //監聽上拉加載事件
        //    this.scroll.on('pullingUp',()=>{
        //        //發射一個自定義事件
        //        this.$emit('pullingUp');
        //    });
    },
    methods: {
        //返回頂部
        scrollTop(x, y, time = 300) {
            //給它在外面做一層封裝, 給它設置一個默認的滾動時間,300毫秒;
            this.scroll.scrollTo(x, y, time);
        },
        //每當圖片加載完成后,重新計算可滾動的區域
        refresh() {
            this.scroll && this.scroll.refresh();
            // 因為this.scroll是寫在mounted中
            //怕存在 還沒有值的情況就調用函數;
            //意思是只有當 this.scroll 創建完成后 才會執行 this.scroll.refresh()
        },
        //當上拉加載事件完成后,調用此方法,才可以進行下一次上拉加載;
        finishPullUp() {
            this.scroll && this.scroll.finishPullUp();
        }
    }
};
</script>

<style lang="less">
.wrapper {
    height: calc(
        100vh - 96px
    ); //切記使用 calc 的時候,里面的 - 左右兩邊一定要有個空格,快被這個bug搞死了;
    background-color: #fff;
    overflow: hidden;
    margin-top: 46px;
}
</style>
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM