<template>
<div id="home">
<!-- tab -->
<div class="header_box">
<span
v-for="(item, index) in tabs"
:key="index"
class="header"
@click="choseTabs(item.tab)"
:class="cur === item.tab ? 'active' : ''"
>
{{ item.name }}
</span>
</div>
<!-- main -->
<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<van-list
:error.sync="error"
error-text="请求失败,点击重新加载"
v-model="loading"
:finished="finished"
finished-text="没有更多了"
@load="onLoad"
class="main"
>
<van-cell v-for="(item, index) in list" :key="index">
{{ item.title }}
</van-cell>
</van-list>
</van-pull-refresh>
<top></top>
</div>
</template>
<script>
import { topics } from "../../network/api";
export default {
data() {
return {
tabs: [
{
name: "全部",
tab: "all",
},
{
name: "精华",
tab: "good",
},
{
name: "分享",
tab: "share",
},
{
name: "问答",
tab: "ask",
},
{
name: "招聘",
tab: "job",
},
],
// 后端接口参数
params: {
tab: "all",
page: 1,
},
list: [],
cur: "all",
loading: false,
finished: false,
error: false,
isTab: true, //点tab请求数据不合并,只有下滑触底变成false
flag: false, //默认请求第一页
refreshing: false,
};
},
methods: {
onLoad() {
//下滑触底事件,只有下滑触底变成false 合并数据
this.isTab = false;
this.params.page++;
this.getTopics();
},
async getTopics() {
await topics(this.params)
.then((res) => {
// console.log(res);
if (this.isTab) {
this.list = res; //一开始渲染不拼接 思路一开始和点击tab渲染不拼接 否则拼接数据
} else {
this.list = [...this.list, ...res]; //否则false拼接 总数据在前,请求在后
}
this.loading = false;
this.isTab = true; //拼接完=false 重新打开页面是否是初始值true
})
.catch((err) => {
this.error = false;
});
},
choseTabs(tab) {
window.scrollTo(0, 0);
this.params.page = 1;
this.cur = tab;
this.params.tab = tab;
this.getTopics();
},
// -------------
onRefresh() {
// 清空列表数据
this.params.page = 1;
// 重新加载数据
this.getTopics();
// 将 loading 设置为 true,表示处于加载状态
this.loading = false;
},
},
// -------------
computed: {},
components: {},
created() {
this.getTopics();
},
};
</script>
<style lang="scss" scoped>
#home {
height: 100%;
width: 100%;
.header_box {
background-color: #eee;
width: 100%;
position: fixed;
z-index: 999;
top: 0;
height: 50px;
line-height: 50px;
display: flex;
text-align: center;
.header {
flex-basis: 20%;
}
.active {
color: red;
background-color: green;
}
}
.main {
margin-top: 40px;
}
}
</style>
上拉加载更多
这是一个关于Vue.js的前端应用实现。通过遍历`tabs`数组创建导航栏,点击不同选项切换数据源。使用`van-pull-refresh`和`van-list`组件实现上拉加载更多功能,同时提供下拉刷新。初始加载和点击tab时不合并数据,下滑触底时合并数据。`getTopics`方法负责获取数据,`onLoad`和`onRefresh`处理加载和刷新逻辑。
摘要由CSDN通过智能技术生成