英文:
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) => {
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 'svelte/store';
import authStore from './stores'
export const load = async () => {
return get(authStore); // gets the current value
}
And then in your page.svelte you can import that data like so:
<script>
export let data;
console.log(data); // contains whatever load() returned, so the value of authStore
</script>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论