[英]Vue3 Ghost script setup api call with page filter
我仍然對 Vue3 腳本設置語法有點熟悉。 為此,我試圖了解如何將分頁與動態 API 調用集成。
<script setup>
import GhostContentAPI from '@tryghost/content-api'
import { ref } from "vue";
const api = new GhostContentAPI({
url: 'https://demo.ghost.io',
key: '22444f78447824223cefc48062',
version: "v5.0"
});
const pagestart = ref(1);
let posts = [];
const allposts = async () => {
await api.posts
.browse({
page: pagestart.value,
limit: "6",
include: "tags,authors,slug",
})
.then((response) => {
let posts = response
console.log(posts)
})
.catch(err => {
console.error(err);
})
};
watch(pagestart, (newValue, oldValue) => {
console.log(newValue, oldValue);
if(newValue !== oldValue){
allposts();
}
});
onMounted(() => {allposts(); })
</script>
所以我不明白的是如何在當前頁面更改時使調用刷新。 到目前為止,我可以在控制台中看到 api 調用發生了變化,但內容沒有刷新,也沒有在頁面加載時加載
您可以嘗試通過以下方式讓 api 撥打watch
<script setup>
import { ref } from "vue";
const api = new GhostContentAPI({
url: 'https://demo.ghost.io',
key: '22444f78447824223cefc48062',
version: "v5.0"
});
const currentpage = ref(1)
const allposts = () => {
return await api.posts
.browse({
page: currentpage.value,
limit: "6",
include: "tags,authors,slug",
})
.catch(err => {
console.error(err);
})
};
watch(currentpage, (newValue, oldValue) => {
console.log(newValue, oldValue);
if(newValue !== oldValue){
allposts();
}
});
</script>
在觀察者中,我們檢查反應式currentPage
的值是否改變,如果改變了,我們從觀察者調用 api。
每次更改currentPage
時調用都會刷新。
我最終使用的是:
仍然必須將等待包裝在異步中 function 仍然必須將響應與 posts.value 相匹配
<script setup>
import GhostContentAPI from "@tryghost/content-api";
import { ref, watch } from "vue";
const api = new GhostContentAPI({
url: 'https://demo.ghost.io',
key: '22444f78447824223cefc48062',
version: "v5.0"
});
const pagestart = ref(1);
const allposts = async () => {
await api.posts
.browse({
page: pagestart.value,
limit: "6",
include: "tags,authors,slug",
})
.then((response) => {
posts.value = response;
console.log(posts);
})
.catch((err) => {
console.error(err);
});
};
watch(pagestart, (newValue, oldValue) => {
console.log(newValue, oldValue);
if (newValue !== oldValue) {
allposts();
}
});
const posts = ref(allposts());
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.