**闲白儿:
我很少写文章,直到面试时被问到:你平时写技术文章吗?你项目中的难点在哪里?等等这类问题时,开始意识到自己不怎么擅长总结归纳,有时候项目中遇到的难题当时解决了,没有记录,自己也没放心上,我记性也不是很好。面试被问确实有些懵逼,所以目前在培养记录的习惯,想把工作或学习中遇到的问题跟大家分享,同时也想鞭策自己。废话不多说,开始正题 *__*
本文结合项目中遇到的无限滚动加载遇到的问题展开讨论。
问题:无限滚动,在筛选的时候数据总是显示重复的问题 原因: 我虽然对每次的列表进行清空了,但是忘记初始化当前页数(count=0)和总页数(totalPages=0) 解决方案:如下,附上项目中该问题的代码,也希望能帮助大家少走弯路。
需要注意的是本项目的当前页数(count)是从0开始,如果你的项目是从1开始,需作适当调整。
html
<div class="infinite-list-wrapper">
<div>
<el-select
class="float-right"
v-model="typeValue"
placeholder="请选择"
@change="filter"
>
<el-option
v-for="item in typeList"
:key="item.value"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
</div>
<ul
class="temlist"
v-infinite-scroll="load"
infinite-scroll-disabled="disabled"
>
<li class="item" v-for="item in templateList">
<div class="header">
<h3>ID:{{ item.id }}</h3>
</div>
<div class="content">
<img class="img-3" src="@/static/phone.png" alt="" />
</div>
</li>
</ul>
<p v-if="loading" class="loading">加载中...</p>
<p v-if="noMore" class="no-more">--没有更多了--</p>
</div>
script
export default {
data() {
typeValue: 0,
typeList: [
{
label: "全部",
value: 0,
},
{
label: "通用",
value: 1,
},
{
label: "专属",
value: 2,
},
]
}
},
computed: {
noMore() {
//当起始页数大于总页数时停止加载
return this.count >= this.totalPages-1;
},
disabled() {
return this.loading || this.noMore;
},
},
methods: {
load() {
this.loading = true;
this.count += 1; //页数+1
this.getTemplateList();
},
// 筛选
filter(e) {
let that = this;
that.typeValue = e;
that.count = 0; // 当前页,这一步很重要,初始化当前页,防止数据显示不正确
that.totalPages = 0; // 这一步很重要,重置总页数,防止滑动时数据重复,与noMore()相关
setTimeout(() => {
that.templateList = []; // 这一步很重要,清空上一次列表数据
that.getTemplateList();
},1000)
},
getTemplateList() {
let that = this;
let param = {
page: that.count,
size: that.size,
type: that.typeValue,
storeId: storeId,
};
queryPage(param)
.then((res) => {
if(res.data.content.length){
// 每请求一次拼接数组
that.templateList = that.templateList.concat(res.data.content);
// 总页数的计算: 如果能整除就取相除的值,如果不能整除则向上取整
that.totalPages = res.data.totalElements % that.size === 0 ?(res.data.totalElements / that.size): Math.ceil(res.data.totalElements / that.size);
}
this.loading = false;
})
.catch((error) => {
this.loading = false;
});
},
}
结束
有不对的欢迎指正