如何将数据从 Svelte 存储获取到 +page.js?

huangapple go评论50阅读模式
英文:

How to get data from a Svelte store to +page.js?

问题

+page.svelte中,我导入了我的store,如下所示:

import { authStore } from '../stores/authStore';

然后,我可以像这样从store中访问用户ID:

let uid;
authStore.subscribe((curr) => {
	uid = curr?.currentUser?.uid;
});

但是我如何在+page.js中访问它呢?console.log('uid: ', uid);将给我输出uid: undefined

好的,我可以将它存储在Cookie中,但那并不太安全。

英文:

In the +page.svelte I import my store import { authStore } from '../stores/authStore'; and then I can access the user ID from the store like this:

let uid;
authStore.subscribe((curr) => {
	uid = curr?.currentUser?.uid;
});

But how can I access it in the +page.js? console.log('uid: ', uid); will give me uid: undefined

OK, I can store it in the cookies but that is not that secure.

答案1

得分: 2

代码部分已翻译如下:

// 在 page.js 中订阅 authStore
authStore.subscribe((curr) => {
    uid = curr?.currentUser?.uid;
});
// 在 page.js 中加载数据
import { get } from 'svelte/store';
import authStore from './stores';

export const load = async () => {
    return get(authStore); // 获取当前值
}
<!-- 在 page.svelte 中导入数据 -->
<script>
    export let data;
    console.log(data); // 包含 load() 返回的内容,即 authStore 的值
</script>

请注意,以上内容只翻译了代码部分,没有包括问题本身或其他非代码的内容。

英文:

It's a little unclear what you're actually trying to do, but variables aren't shared between page.svelte and page.js by default, so of course uid is going to be undefined in page.js. You could just subscribe to it in page.js exactly like you were doing in page.svelte:

authStore.subscribe((curr) =&gt; {
    uid = curr?.currentUser?.uid;
});

However, the typical reason to even have a page.js file is to populate the data needed for page.svelte by means of a load function which gets called first. So you probably want to do something more along the lines of:

import { get } from &#39;svelte/store&#39;;
import authStore from &#39;./stores&#39;

export const load = async () =&gt; {
    return get(authStore); // gets the current value
}

And then in your page.svelte you can import that data like so:

&lt;script&gt;
    export let data;
    console.log(data); // contains whatever load() returned, so the value of authStore
&lt;/script&gt;

Again, there's not a lot of detail in your question that would explain why you want to get the value of authStore in the .js rather than in the .svelte file, so it's hard to say if that even makes sense.

huangapple
  • 本文由 发表于 2023年5月28日 16:38:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76350620.html
  • svelte
  • svelte-store
  • sveltekit

Svelte JS 和 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定