我知道 sapper 中的 session 是一个可写存储。 我可以这样写:
<script>
import { stores } from "@sapper/app"
const { session } = stores()
session.set("new value")
</script>
但是,我很难在预加载函数中写入:
<script context="module">
export async function preload(page, session) {
session = "new value" // not working, this is just a value, not a store
}
</script>
我需要在 _layout.svelte
预加载期间设置一些数据。有什么支持的方法吗?
编辑 我最终根本不使用 session ,只是一个简单的可写存储。它不是那么干净,但它达到了目的。如果有人找到方法或将来得到支持,请将其保持打开状态。
最佳答案
这里的session
参数不是 session 存储,而是其他东西。 the docs 中对此进行了赞扬。 :
session is generated on the server by the session option passed to sapper.middleware (TODO this needs further documentation. Perhaps a server API section?)
编辑:
[之前的建议因不正确而删除]
为了完整性:显然,session
与session
存储相关,参数是存储的值。不过,您仍然无法以有意义的方式写入它。
就像我在评论中所说的那样,我认为您想要做的事情在预加载
中是不可能的。也许我错了,其他人可能会告诉你。
同时,我建议采用以下解决方法:在 _layout 组件实例中执行所有这些操作。在那里你可以完全进入商店。例如这样的事情:
<script>
import { stores } from '@sapper/app'
import { resolveAuth } from './your/utils'
const { session } = stores()
resolveAuth()
.then(auth => { $session = auth })
.catch(err => { ... })
</script>
{#if $session}
<slot />
{:else}
<!-- loading indicator... or not -->
{/if}
关于svelte - 如何在预加载期间写入 session 存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59145105/