Snapshots
临时 DOM 状态——如侧边栏的滚动位置、<input>元素的内容等——在您从一个页面导航到另一个页面时会被丢弃。
例如,如果用户填写了表单但在提交前离开并返回,或者如果用户刷新了页面,他们填写的值将会丢失。在需要保留输入的情况下,您可以对 DOM 状态进行快照,这样在用户返回时可以恢复。
为此,从snapshot对象中导出具有capture和restore方法的+page.svelte或+layout.svelte:
+page
<script>
let comment = $state('');
/** @type {import('./$types').Snapshot<string>} */
export const snapshot = {
capture: () => comment,
restore: (value) => comment = value
};
</script>
<form method="POST">
<label for="comment">Comment</label>
<textarea id="comment" bind:value={comment} />
<button>Post comment</button>
</form><script lang="ts">
import type { Snapshot } from './$types';
let comment = $state('');
export const snapshot: Snapshot<string> = {
capture: () => comment,
restore: (value) => comment = value
};
</script>
<form method="POST">
<label for="comment">Comment</label>
<textarea id="comment" bind:value={comment} />
<button>Post comment</button>
</form>当你离开此页面时,页面更新之前立即调用 捕获 函数,返回的值与浏览器历史记录栈中的当前条目相关联。如果你返回,页面更新后立即使用存储的值调用 恢复 函数。
数据必须可序列化为 JSON,以便持久化到sessionStorage。这允许在页面重新加载或用户从不同网站返回时恢复状态。
[!注意] 避免从
capture返回非常大的对象 — 一旦捕获,对象将在会话期间保留在内存中,在极端情况下可能太大而无法持久化到sessionStorage。
Edit this page on GitHub llms.txt
previous next