- 上拉加载 onLoad
第一步:导入api接口真实数据模块src/api/article.js
在 src/vies/home/index.vue
中的script里
import { getArticles } from ‘@/api/article’
第二步: src/vies/home/index.vue
中的methods里
async onLoad () {
// 注意:请勿模仿 真实的开发不需要的。
await this.$sleep()
// 当前选中的频道ID,时间戳
// 动态获取当前频道的数据
const data = await getArticles(this.activeChannel.id, this.activeChannel.timestamp)
// 给数据赋值 追加
this.activeChannel.articles.push(...data.results)
// 把加载中状态 加载结束
this.activeChannel.upLoading = false
// 如果数据加载完毕 pre_timestamp 值null 没有下一页
if (!data.pre_timestamp) {
this.activeChannel.finished = true
} else {
// 将来会继续加载
this.activeChannel.timestamp = data.pre_timestamp
}
},
-
下拉刷新 onRefresh
src/vies/home/index.vue
中的methods里
await this.$sleep()
// 当前频道的ID和时间戳 刷新 使用最新的时间戳
this.activeChannel.timestamp = Date.now()
const data = await getArticles(this.activeChannel.id, this.activeChannel.timestamp)
// 停止刷新效果
this.activeChannel.downLoading = false
if (data.results.length) {
// 替换 articles 数据
this.activeChannel.articles = data.results
this.refreshSuccessText = '更新成功'
// 把当前的时间戳 替换成后台给你的 获取下一页需要的数据
this.activeChannel.timestamp = data.pre_timestamp
// 把之前全部加载完毕的状态改成 没有全部加载完毕
this.activeChannel.finished = false
// 防止加载的数据不够一屏 主动加载一次数据
this.onLoad()
} else {
this.refreshSuccessText = '暂无更新'
}
}
- 渲染页面
<van-pull-refresh v-model="activeChannel.downLoading" @refresh="onRefresh" :success-text="refreshSuccessText">
<van-list v-model="activeChannel.upLoading" :finished="activeChannel.finished"
finished-text="没有更多了" @load="onLoad">
<van-cell-group>
<van-cell v-for="article in activeChannel.articles"
:key="article.id" :to="'/article/'+article.art_id">
<div class="article_item">
<h3 class="van-ellipsis">{{article.title}}</h3>
<div class="img_box" v-if="article.cover.type === 3">
<van-image class="w33"
fit="cover"
:src="article.cover.images[0]"/>
<van-image class="w33"
fit="cover"
:src="article.cover.images[1]"/>
<van-image class="w33"
fit="cover" :src="article.cover.images[2]"/>
</div>
<div class="img_box" v-if="article.cover.type === 1">
<van-image class="w100"
fit="cover" :src="article.cover.images[0]"/>
</div>
<div class="info_box">
<span>{{article.aut_name}}</span>
<span>{{article.comm_count}}评论</span>
<span>{{article.pubdate}}</span>
<span class="close">
<van-icon name="cross"></van-icon>
</span>
</div>
</div>
</van-cell>
</van-cell-group>
</van-list>
</van-pull-refresh>
- 工具函数 $sleep 新建
src/utils/plugin.js
在src/main.js中进行引入:
//注册 自定义 基于vue的功能
import plugin from @/utils/plugin’
Vue.use(plugin)
// 提供 一些工具函数 或者 过滤器 或者 自定义指令 以插件形式存在
/**
* 做一秒的延时 工具函数
*/
const sleep = () => {
return new Promise((resolve, reject) => {
window.setTimeout(() => {
resolve()
}, 1000)
})
}
export default {
install (Vue) {
// 实现需要的东西
Vue.prototype.$sleep = sleep
}
}