有一个页面显示学生列表。它应该支持分页(通过
?page=
)。
从
?page=0
到 ?page=1
-> 页面已更新
从
?page=1
返回到?page=0
-> 页面未更新(除非我通过invalideAll:true
- goto('?page=0', { invalidateAll:true })
)
// +page.ts
import type { PageLoad } from './$types';
export const prerender = true;
export const load: PageLoad = async ({ fetch, url }) => {
const selected_page = parseInt(url.searchParams.get("page") || "0");
const res = await fetch(`/api/student-list?page=${selected_page}`); // make sure there are no trailing slashes, otherwise bug https://stackoverflow.com/questions/78734150/sveltekit-redirect-308-when-trying-to-access-internal-api-from-page-server-ts
const response = await res.json();
response.selected_page = selected_page + 1;
console.log("load() selected page=", selected_page);
return response;
};
<!-- +page.svelte -->
<script lang="ts">
import Pagination from "../../components/pagination.svelte";
/** @type {{ data: import('./$types').PageData }} */
import { page as g_page } from "$app/state";
import { goto } from "$app/navigation";
const { data } = $props();
const _ = $derived(data); // to make sure when 'data' is updated, things are re-rendered
const __ = $derived(g_page.url.searchParams);
function page_clicked(page_arg: number) {
g_page.url.searchParams.set("page", (page_arg - 1).toString());
goto(g_page.url);
}
</script>
<Pagination custom_class="mb-8"
onPageClick={page_clicked}
selected_page={data.selected_page}
total={data.total}
/>
有办法解决这个问题吗?这是设计使然吗?
您不应该修改现有的页面状态 URL,它会破坏
goto
逻辑,第一次修改后将确定源 URL 和目标 URL 相同,因此不会发生任何情况。
创建一个新的 URL:
const newUrl = new URL(g_page.url);
newUrl.searchParams.set("page", (page_arg - 1).toString());
goto(newUrl);