英文:
Cannot bind to a variable declared with {#await ... then} or {:catch} blocks}
问题
这是一个很好的错误解释,但我不知道如何解决它。
我有一个+layout.js文件,返回一个异步的load函数:
import { api } from '$lib/utils/api';
/** @type {import('./$types').PageLoad} */
export async function load() {
const fetchUserData = async () => {
return await api.auth.user();
};
return {
stream: {
user: fetchUserData()
}
};
}
然后在+page.svelte中,我使用{#await}加载这个数据:
<script>
export let data;
let { stream } = data;
</script>
{#await stream.user then user}
<input type="text" bind:value={user.data.gender} />
{/await}
由于在等待完成之前我没有这些用户数据,所以我不知道如何将其绑定到输入框,如果我不能使用bind:value的话。我在文档中找不到任何相关信息。
英文:
This is a nice error explanation but I don't know how to solve it.
I have a +layout.js that returns a load function async:
import { api } from '$lib/utils/api';
/** @type {import('./$types').PageLoad} */
export async function load() {
const fetchUserData = async () => {
return await api.auth.user();
};
return {
stream: {
user: fetchUserData()
}
};
}
Then in the +page.svelte I load this data with {#await}
<script>
export let data;
let { stream } = data;
</script>
{#await stream.user then user}
<input type="text" bind:value={user.data.gender} />
{/await}
Since I don't have those user data before the await finishes, I don't know how to bind it to the input if I cannot use bind:value. I cannot find anything from the documentation.
答案1
得分: 1
你可以将块的内容提取到一个单独的组件中。我强烈建议这样做,因为 user 只在 {#await} 块中可用,否则无法直接在 <script> 部分中使用。
{#await ... then user}
<UserEditor {user} />
{/await}
然后,在 UserEditor 内,你可以像往常一样进行绑定。
<script>
export let user;
</script>
<input bind:value={user.data.gender} />
英文:
You can extract the contents of the block to a separate component. I would recommend this anyway because user is scoped to the {#await} block and cannot be worked with directly in the <script> part otherwise.
{#await ... then user}
<UserEditor {user} />
{/await}
Inside UserEditor you then can bind as usual.
<script>
export let user;
</script>
<input bind:value={user.data.gender} />
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论