Vue混入mixins滚动触底的方法

2020-06-12 20:48:51易采站长站整理

</div>
created(){
// 初始化数据
this.list = Array.from(Array(10),(item,index)=>index)
// 通过监听滚动事件来判断 可视区域 , 滚动高度 ,文档高度的关系
window.addEventListener('scroll',()=>{
let isBottom = (getScrollHeight() + getWindowHeight()) >= getDocumentTop()
if(isBottom){
console.log('触底了',new Date())
let list = this.list
let last = list[list.length-1] let newList = Array.from(Array(10),(item,index)=>index+last+1)
this.list.push(...newList)
}
})
}

优化和复用滚动事件逻辑

将滚动逻辑抽取成 mixins 放在 scroll.js 中。优化功能点如下:

增加触底距离
滚动事件监听事件节流
添加触底动画,并将 UI 样式一起封装在 scroll.js 中

 模拟请求事件

为了模拟请求数据,封装了一个 Promise 一秒后返回结果


methods:{
// 返回一个 promise ,用于请求服务端数据
findDataList(){
let list = this.list
let last = list[list.length-1] return new Promise((resolve)=>{
// 模拟服务端数据
let newList = Array.from(Array(10),(item,index)=>index+last+1)
setTimeout(() => {
resolve(newList)
}, 1000);
})
}
}

滚动事件监听

滚动事件触发,判断当前是否触底,触底了以后去执行 loadMore 发起请求拿取服务端的数据


created(){
let fn = throttle(()=>{
let isOver = (getScrollHeight() + getWindowHeight()) >= (getDocumentTop()- MIN_INSTANCE)
// 触底时进行数据加载
if(isOver){
// 创建加载组件
this.loadMore&&this.loadMore()
}
},DEALY_TIME)
window.addEventListener('scroll',fn)
},

添加触底动画

因为我们是将逻辑抽离在 mixins中,为了把触底动画也集成在里面使用 Vue.extend() 来实现编程式插入UI样式的方法。

首先定义好 loading 组件的样式


<template>
<div id="loading-alert">
<i class="el-icon-loading"></i>
<span>{{ message }}</span>
</div>
</template>

<script>
export default {
props:{
message:{
type:String,
default:'正在加载更多数据'
}
},
};

当触底时去插入这个 loading 组件


import load from './load.vue'
data(){
return {
isLoading:false,
component:null
}
},
created(){
let fn = throttle(()=>{
let isOver = (getScrollHeight() + getWindowHeight()) >= (getDocumentTop()- MIN_INSTANCE)