问题描述
我对 svelte/Sapper 很陌生,所以请耐心等待。我有一个从 API url 获取的动态路由,并且根据“包”它应该呈现不同的组件。该路由在加载或刷新时工作正常,但是当在页面之间单击时,它不会检测到“包”并尝试加载错误的组件:
[...slug].svelte
<script context="module">
export async function preload({ params }) {
const res = await this.fetch(process.env.sveLTE_APP_API_URL + '/alias?_format=json&slug='+ params.slug);
if (res.status === 200) {
const data = await res.json();
return { node: data };
} else {
this.error(res.status,data.message);
}
}
</script>
<script>
import Article from '../bundles/Article.svelte';
import Page from '../bundles/Page.svelte';
import CustomPage from '../bundles/CustomPage.svelte';
import Error from './_error.svelte';
export let node;
const bundles = {
article: Article,page: Page,custom_page: CustomPage
};
let Component;
let status = '';
let error = {
message: ''
};
if(bundles[node.bundle]){
Component = bundles[node.bundle];
}else{
Component = Error;
status = '404';
error.message = 'Page not found';
}
</script>
{node.bundle} // This is correct!
{#key [node.bundle]}
<svelte:component node={node} status={status} error={error} this={Component}/>
{/key}. // This is incorrect!
它确实获取了正确的数据 - 如果我在两个不同的“页面”包之间单击,它会呈现正确的内容。
如果我以完全错误的方式处理事情,请告诉我:)
解决方法
我发现我必须使组件变量具有反应性:
$: component = bundles[node.bundle];