先看效果:
再上代码
<template>
<div class="pageRoot">
<van-nav-bar title="威哥头条" fixed />
<van-pull-refresh v-model="isLoading" @refresh="onRefresh">
<van-list
v-model="loading"
:finished="finished"
finished-text="没有更多数据了"
@load="onLoad">
<article_item v-for="(item,index) in articleList"
:key="item.art_id"
:art_id="item.art_id"
:title="item.title"
:comm_count="item.comm_count"
:pubdate="item.pubdate"
:aut_name="item.aut_name"
:cover="item.cover">
</article_item>
</van-list>
</van-pull-refresh>
</div>
</template>
<script>
import {getArticleListAPI} from '@/api/articleAPI.js'
import article_item from '@/components/AtricleItem.vue'
export default {
data() {
return {
articleList: [],
pageIndex:1,
pageSize:10,
//List 组件通过 loading 和 finished 两个变量控制加载状态,当组件滚动到底部时,会触发 load 事件并将 loading 设置成 true。此时可以发起异步操作并更新数据,数据更新完毕后,将 loading 设置成 false 即可。若数据已全部加载完毕,则直接将 finished 设置成 true 即可。
//是否正在加载下一页数据,如果loading为true,则说明在加载中不会反复触发load事件
//每当下一页数据请求回来之后,要把loading从true改为false
loading:false,
finished:false,//所有的数据是否加载完毕了,如果没有更多数据,则把finished改为true
isLoading:true
}
},
created(){
},
methods: {
//加载文章列表数据
async initArticleList() {
const {data:res}=await getArticleListAPI(this.pageIndex,this.pageSize)
if(res.length==0)//如果数据全部加载完,将finished改为true
{
this.finished=true;
}
else//将加载到的数据添加后文章列表数组中
{
res.forEach(item=>{
this.articleList.push(item);
})
}
this.loading=false;//数据请求完成后将loading改为false
},
onLoad(){
this.pageIndex++;
this.initArticleList();
},
async onRefresh(){//下拉刷新
//下拉刷新时会触发 refresh 事件,在事件的回调函数中可以进行同步或异步操作,操作完成后将 v-model 设置为 false,表示加载完成。
const {data:res}=await getArticleListAPI(1,this.pageSize)
if(res.length>0)
{
res.forEach(item=>{
const arry=this.articleList.filter(art=>art.art_id==item.art_id);
if(arry.length==0)
{
this.articleList.unshift(item);
}
})
}
this.isLoading=false;
}
},
components:{
article_item
}
}
</script>