Vue触底加载

页面内的触底加载

需求:页面滚动到接近底部,再次发送请求,获取更多数据,渲染到页面上

data(){
    // 请求页数
    page:0,
    // 请求获取的数据
    list:[],
    // 是否正在加载,用于节流
    isLoading:false,
},
created(){
    // 首次调用
    this.getList()
    this.bindScroll()
},
methods:{
    // 用于发送请求获取数据的函数
    async getList(){
            this.page++;
            this.isLoading=true;
            // 发送请求
            const data=await axios.get(`api/post/share_list?page=${this.page}`)
            this.isLoading=false
            // 如果获取的数据不为空
            if(data.post_list.length){
                this.list.push(...data.post_list)            
            }
    },
    // 滚动回调函数
    scrollHande(){
        // 节流
        if(this.isLoading) return
        // 获取内容高度
        var scrollH=document.documentElement.scrollHeight
        // 获取窗口高度
        var innerH=window.innerHeight
        // 获取滚出去的内容高度
        var top=document.body.scrollTop || document.documentElement.scrollTop
        // 当内容还剩余200的高度未滚出的时候发送请求
        if(scrollH-top-innerH<200){
            // 发送请求
            this.getList();
        }
    },
    // 绑定scroll事件
    bindScroll(){
        window.addEventListener('scroll',this.scrollHande)    
    },
    // 清除scroll事件
    clearScroll(){
        window.removeEventListener('scroll',this.scrollHande)    
    }
},
// 页面销毁之前,清除scroll
destroyed(){
    this.clearScroll()
}

容器内的触底加载

需求:一个有固定高度的容器,实现容器里面的内容触底加载

// 外层容器
<div ref="container">
    // 内容
    <div ref="inner"></div>
</div>


// script
data(){
    return{
        list:[],
        page:0,
        isLoading:false,//节流
        containerHeight: 0,
        innerHeight:0 
    }
},
created() {
     this.getList();
},
mounted() {
        // 容器高度
        this.containerHeight = this.$refs.container.clientHeight
        // 内容高度
        this.innerHeight = this.$refs.inner.offsetHeight
        // 滚动监听
        this.$refs.container.addEventListener('scroll',this.callBackScroll)
},
methods: {
        // 发送请求
        async getList() {
            this.page++;
            // 打开
            this.isLoading = true;
            // 发送请求
            const data = await axios.get(`v031/card/themes?page=${this.page}`)
            // 关闭
            this.isLoading = false
            // 判断请求是否有数据
            if (data.length) {
                this.list.push(...data)
            }
         },
        // 滚动回调函数
        callBackScroll(e) {
            if (this.isLoading) return
            this.innerHeight = this.$refs.inner.offsetHeight
            let scrollTop = e.target.scrollTop
            // 当滚出去的内容高度加上窗口也就是外部容器的高度大于等于内容高度时发送请求
            if (scrollTop + this.containerHeight >= this.innerHeight) {
                this.getList();
                console.log('到底了~~');
            }
        }
},
//页面销毁之前,清除scroll
destroyed() {
    this.$refs.container.removeEventListener('scroll', this.callBackScroll)
},

猜你喜欢

转载自blog.csdn.net/qq_44774622/article/details/127410036