Sveltekit 在导航到 slug 页面时不具备响应性。

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

Sveltekit is not reactive when navigating through slug page

问题

当我浏览 [slug] 页面时,尽管 +page.server.ts 被正确调用,但内容不会更新。

我理解这是一种预期行为,解决方法是使用"$:" 监听更改并重新评估语句,但这并不起作用。

有什么想法吗?

+page.server.ts

import { getPage } from '$lib/services/pages';
export async function load({ params }) {
    const page = await getPage(params.slug);
    return { page };
}

+page.svelte

<script>
    import Editor from '$lib/editor/index.svelte';
    export let data;
    // 这是在类似问题上找到的解决方案,但这不起作用
    $: content = data.page.text
    // 但这起作用
    $: console.log(data.page.text)

</script>

<Editor {content}></Editor>

注意:导航使用简单的标签在 +layout.svelte 上进行。

编辑:Editor 组件实际上是这个 tiptap svelte 示例 的副本,只是内容通过父组件传递。

谢谢

英文:

When I navigate through [slug] pages, the content does not update although +page.server.ts is correctly called.

I understand this is an expected behavior and that the solution is to use "$:" to listen to change and reevaluate the statement, but this does not work.

Any idea ?

+page.server.ts

import { getPage } from &#39;$lib/services/pages&#39;;
export async function load({params}) {
    const page = await getPage(params.slug)
    return { page };
} 

+page.svelte

&lt;script&gt;
    import Editor from &#39;$lib/editor/index.svelte&#39;
    export let data;
    // This is the solution found on similar question but this does not work
    $: content = data.page.text
    // But this works 
    $: console.log(data.page.text)

&lt;/script&gt;

&lt;Editor {content}&gt;&lt;/Editor&gt;

Note: Navigation is made with simple <a> tag on +layout.svelte

EDIT: the Editor component is actually a copy of this tiptap svelte example except the content is passed through the parent.

Thank you

答案1

得分: 1

可能在“Editor”组件中有类似的错误。
一些您可以尝试的事情

添加以下内容,它将在屏幕上显示您的文本内容并且应该会改变

&lt;pre&gt;{JSON.stringify(content, null, 2)}&lt;/pre&gt;

通过使用“#key”来强制“Editor”组件重新挂载,这可能有效,但根据您的需求,修复组件本身可能更好。

{#key content}
  &lt;Editor {content} /&gt;
{/key}
英文:

Likely you have a similar error in the Editor component.
Some things you can try

add the following, it will make a dump of your text on screen and should change

&lt;pre&gt;{JSON.stringify(content, null, 2)}&lt;/pre&gt;

force the Editor component to remount by using #key, this likely works but it might be better to fix the component itself depending on your needs.

{#key content}
  &lt;Editor {content} /&gt;
{/key}

答案2

得分: 1

我不是专家,但最近遇到了类似/相同的问题。诀窍似乎是要添加括号。像这样:

 $: (content = data.page.text) 
英文:

I'm no expert, but I recently had a similar/same problem. The trick seems to be to add parentheses. Like this:

 $: (content = data.page.text) 

huangapple
  • 本文由 发表于 2023年7月24日 14:51:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752028.html
匿名

发表评论

匿名网友

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

确定