您的位置:首页 > 产品设计 > UI/UE

vue中实现滚动加载更多

2017-06-09 14:11 429 查看
在以前的前端刀耕火种时代要实现滚动加载更多想要大家都是很快实现了,在vue会有一点麻烦,最近自己研究了一下,做了一个简单的demo,供大家参考:

<template>
<div>
<ul>
<li v-for="item in articles">
<h2>{{item.title}}</h2>
<img :src="item.images" alt="">
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default{
data(){
return {
articles : []
}
},
mounted(){
// 缓存指针
let _this = this;
// 设置一个开关来避免重负请求数据
let sw = true;
// 此处使用node做了代理
axios.get('http://localhost:3000/proxy?url=http://news-at.zhihu.com/api/4/news/latest')
.then(function(response){
// console.log(JSON.parse(response.data).stories);
// 将得到的数据放到vue中的data
_this.articles = JSON.parse(response.data).stories;
})
.catch(function(error){
console.log(error);
});

// 注册scroll事件并监听
window.addEventListener('scroll',function(){
// console.log(document.documentElement.clientHeight+'-----------'+window.innerHeight); // 可视区域高度
// console.log(document.body.scrollTop); // 滚动高度
// console.log(document.body.offsetHeight); // 文档高度
// 判断是否滚动到底部
if(document.body.scrollTop + window.innerHeight >= document.body.offsetHeight) {
// console.log(sw);
// 如果开关打开则加载数据
if(sw==true){
// 将开关关闭
sw = false;
axios.get('http://localhost:3000/proxy?url=http://news.at.zhihu.com/api/4/news/before/20170608')
.then(function(response){
console.log(JSON.parse(response.data));
// 将新获取的数据push到vue中的data,就会反应到视图中了
JSON.parse(response.data).stories.forEach(function(val,index){
_this.articles.push(val);
// console.log(val);
});
// 数据更新完毕,将开关打开
sw = true;
})
.catch(function(error){
console.log(error);
});
}
}
});
}
}
</script>
<style lang="less">
*{
margin:0;
padding:0;
}
li{
list-style:none;
}
</style>
大致效果如下:



当然目前只是一个demo,还有更好的解决办法大家自行补充。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: