Skip to main content

快照

当你从一个页面导航到另一个页面时,短暂的 DOM 状态(如侧边栏上的滚动位置、<input> 元素的内容等)将被丢弃。

¥Ephemeral DOM state — like scroll positions on sidebars, the content of <input> elements and so on — is discarded when you navigate from one page to another.

例如,如果用户填写了表单,但在提交之前离开并返回,或者用户刷新了页面,他们填写的值将会丢失。如果保留该输入很有价值,你可以拍摄 DOM 状态的快照,然后在用户导航回时可以恢复该快照。

¥For example, if the user fills out a form but navigates away and then back before submitting, or if the user refreshes the page, the values they filled in will be lost. In cases where it’s valuable to preserve that input, you can take a snapshot of DOM state, which can then be restored if the user navigates back.

为此,从 +page.svelte+layout.svelte 导出具有 capturerestore 方法的 snapshot 对象:

¥To do this, export a snapshot object with capture and restore methods from a +page.svelte or +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>

当你离开此页面时,会在页面更新之前立即调用 capture 函数,并且返回的值与浏览器历史记录堆栈中的当前条目相关联。如果你向后导航,则页面更新后会立即使用存储的值调用 restore 函数。

¥When you navigate away from this page, the capture function is called immediately before the page updates, and the returned value is associated with the current entry in the browser’s history stack. If you navigate back, the restore function is called with the stored value as soon as the page is updated.

数据必须可序列化为 JSON,以便可以将其持久化到 sessionStorage。这允许在重新加载页面时或用户从其他站点导航回来时恢复状态。

¥The data must be serializable as JSON so that it can be persisted to sessionStorage. This allows the state to be restored when the page is reloaded, or when the user navigates back from a different site.

避免从 capture 返回非常大的对象 - 一旦捕获,对象将在整个会话期间保留在内存中,在极端情况下可能太大而无法持久保存到 sessionStorage

¥[!NOTE] Avoid returning very large objects from capture — once captured, objects will be retained in memory for the duration of the session, and in extreme cases may be too large to persist to sessionStorage.

上一页 下一页