-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.js
74 lines (63 loc) · 1.54 KB
/
app.js
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
const { createApp, ref, onMounted } = Vue;
const Posts = {
template: `
<ul>
<slot></slot>
</ul>
`,
};
const Post = {
props: ["title", "permalink"],
template: `
<li>
<h3 v-html="title"></h3>
<a :href="permalink">Read More</a>
<hr />
</li>
`,
};
const App = {
components: { Posts, Post },
setup() {
const greeting = ref("Load more Posts Vue + WP REST API");
const page = ref(0);
const posts = ref([]);
const totalPages = ref("");
const perPage = ref(4);
const apiURL = `https://wordpress.org/news/wp-json/wp/v2/posts?per_page=${perPage.value}&page=`;
const isLoading = ref("");
const show = ref(true);
const getPosts = () => {
const xhr = new XMLHttpRequest();
page.value++;
isLoading.value = "is-loading";
xhr.open("GET", apiURL + page.value);
xhr.onload = () => {
totalPages.value = xhr.getResponseHeader("X-WP-TotalPages");
if (page.value == totalPages.value) {
show.value = false;
}
const newPosts = JSON.parse(xhr.responseText);
newPosts.forEach((element) => {
posts.value.push(element);
});
isLoading.value = null;
};
xhr.send();
};
onMounted(() => {
getPosts();
});
return {
greeting,
page,
posts,
totalPages,
apiURL,
isLoading,
show,
getPosts,
};
},
};
createApp(App).component("Posts", Posts).component("Post", Post).mount("#app");