【发布时间】:2020-09-15 10:26:28
【问题描述】:
当用户使用 Svelte 和 Sapper 单击页面底部的按钮时,我被困在获取更多数据的部分。
这是代码。
<script context="module">
export function preload(page) {
return this.fetch(`https://reqres.in/api/users?page=${$count}`) // I know this is not goint to work. but when the button is clicked, I want to fetch page 2 and merge it with page 1 data, show data in ascending order(page1, page2)
.then(res1 => {
return res1.json()
}).then(res2 => {
return {
currentPage: res2.page,
per_page: res2.per_page,
notices: res2.data,
total: res2.total,
totalPage: res2.total_pages
}
})
}
</script>
<script>
import { count } from '../../store.js'; // export const count = writable(1); from store.js file
export let currentPage; // 1
export let per_page; // 6
export let notices;
export let total; // 12
export let totalPage; // 2
const handleClick= () => {
if ($count < totalPage) {
count.update(n => n + 1); // update count 1 to 2 and want to deliver changed value to fetch new page
}
}
</script>
<main>
<div id="container">
<h1 class="cont-tit">Notice Board</h1>
<div class="noti-list-wrap">
{#each notices as notice, i}
<ul class="noti-list">
<li>
<a rel=prefetch href={`notice/${notice.id}`}>
<p class="tit">{`${notice.first_name} ${notice.last_name}`}</p>
<hr />
<p class="date">
{`notice no.${i}`}
</p>
</a>
</li>
</ul>
{/each}
<div class="show-more" on:click={handleClick}>show me more</div>
</div>
</div>
</main>
起初我以为我可以使用 $count 来获取第 2 页的数据,但是 script context="module" 中的 import count store 不起作用。
有没有办法将改变的 store 值传递给函数预加载?
【问题讨论】:
标签: javascript svelte sapper