前言
这期是后来补上的,有点忘了写到哪了,缺哪部分大家自行去项目源码上找
项目地址:https://github.com/cctyl/sunofbeach_mobile.git
之前的逻辑,只是把文章列表给展示出来了,但是整体滑动起来,比较不顺滑。
现在想给文章列表加上一个滑动效果。
实现
依然使用nutui的 scroller组件
https://nutui.jd.com/2x/#/scroller
但是有个注意点,这个scroller套在哪里?
如果只套在文章列表部分,那就只有文章列表可以滑动,上方一直都会是轮播图。所以这里,我把scroller套在最外层
套上去之后,开始做一些效果。
比如上拉加载:
上拉加载
在scroller组件上,绑定
@loadMore="loadMoreVert"
:is-un-more="isUnMore"
unloadMoreTxt="到底了"
于此同时,在data中声明 isUnMore: false,//对于滑动组件,是否没有更多数据
,如果这个值是true,就会显示 ”到底了“
methods中添加一个 loadMoreVert
方法
它的思路是这样的,当页面不断的往下滑动,到达了页面底部,就会触发loadMoreVert方法
此时,我们就再发一个请求,加载更多的文章数据,这就是分页查询(这部分我把之前的getArticleList方法重构了,为了适应面更广)
大家看我具体代码:
/**
* 上拉加载更多
*/
loadMoreVert() {
this.isUnMore = true
this.getArticleList(++this.currentPage, true)
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.isUnMore = false
}, 300)
},
下一步我们看下这个 getArticleList方法,里面有一些逻辑:
稍微复杂一点的就是那个去重操作
我拿到第一页的数据,接着我请求了第二页的数据,你会发现它有些数据与第一页的重复。因为推荐数据,本身就是在一直变化中的。
去重的思路
async getArticleList(page = 1, isMerge = false) {
let result = null
//如果有categoryId,说明获取的是标签数据,如果没有,那获取的就是推荐页面的数据
if (this.currentTagId) {
console.log('获取文章数据,不是推荐页,id为:' + this.currentTagId)
result = await api.getArticleListByCategoryId(this.currentTagId, page)
} else {
console.log('获取文章数据,是推荐页,id为:' + this.currentTagId)
result = await api.getRecommendArticleList(page)
}
if (isMerge) {
//合并之前和现在的数据
//合并之前,涉及到一个去重问题
let obj = {}
for (let i = 0; i < this.recommendArticleList.length; i++) {
obj[this.recommendArticleList[i].id] = this.recommendArticleList[i]
}
for (let i = 0; i < result.data.list.length; i++) {
//如果拿着你的id去 obj 里找,找不到,说明原本的 this.recommendArticleList没有这个对象
if (!obj[result.data.list[i].id]) {
this.recommendArticleList.push(result.data.list[i])
} else {
// console.log(result.data.list[i].name + '不会被添加')
}
}
} else {
//更新数据
this.recommendArticleList = result.data.list
}
this.$nextTick(() => {
this.isSkeletonLoading = false
})
},
下拉刷新
首先在scroller组件上绑定一个属性和一个方法
@pulldown="pulldown"
:is-loading="isLoading"
对应的,data中添加: isLoading: false,//是否正在下拉刷新数据
methods中添加 pulldown 方法。
实现思路,当我们在顶部往下拉,这时候就会触发pulldown方法,此时把 isLoading设置为true,然后顶部就会显示加载图标。同时,我们发送请求,获取文章数据,然后把数据直接替换掉原本的数据,就实现了下拉刷新
/**
* 下拉刷新
*/
pulldown() {
this.isLoading = true
this.getArticleList(0, false)
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.isLoading = false
}, 300)
},