vue 滚动加载

在很多场景下,我们需要使用vue滚动加载,数据不断的接上去。

可以参考如下: 问题下的回答列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>滚动加载</title>
</head>
<body>
<div class="container">
hello
</div>
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.staticfile.org/axios/0.15.3/axios.min.js"></script>
<script>
var vue = new Vue({
el: '.container',
data: {
question_id: '',
question: {},
answers: [],
page_size: 10,
page_index: 1,
load_more: false,
is_requesting: false
},
created: function created() {
this.question_id = '5992ab1871e8596697274117';

if (this.question_id) {
this.getQuestionDetail();
this.getQuestionAnswers();
}
},
methods: {
getQuestionDetail: function getQuestionDetail() {
var self = this;
var questionID = this.question_id;

axios.get('/api/question/' + questionID).then(function (res) {
var result = res.data.result;

if (result && result.ok) {
self.question = {
title: result.question_title,
type: result.question_type,
describe: result.question_describe,
answer_count: result.question_answer_count,
view_count: result.question_view_count,

user_id: result.user_id,
user_name: result.user_name,
user_avatar: result.user_avatar
};
}
});
},
getQuestionAnswers: function getQuestionAnswers() {
var self = this;
var questionID = this.question_id;

if (!self.is_requesting) {
self.is_requesting = true;

axios.get('/api/question/answers/' + questionID, {
page_size: self.page_size,
page_index: self.page_index++
}).then(function (res) {
self.is_requesting = false;
var result = res.data.result;

if (result && result.ok) {
self.answers = self.answers.concat(result.list);
self.load_more = result.list.length == self.page_size;
}
}, function (err) {
self.is_requesting = false;
});
}
},
},
mounted: function mounted() {
var self = this;

window.addEventListener('scroll', function () {
if (document.body.scrollTop + window.innerHeight >= document.body.offsetHeight && self.load_more) {
self.getQuestionAnswers();
}
});
}
});
</script>
</body>
</html>

这种实现方式即实现了滚动加载,又不会多次请求api