【问题标题】:Is there a way to make dynamically queries using SvelteKit load function?有没有办法使用 SvelteKit 加载函数进行动态查询?
【发布时间】:2023-03-31 23:10:01
【问题描述】:

我一直试图在 SvelteKit 中使 Strapi's filter parameter 动态化。

使用 insomnia,后端像往常一样根据参数过滤帖子。

我正在尝试使用来自苗条load function 的页面对象。根据文档,它的 {query} 对象是URLSearchParams 接口的一个实例。

我创建了“搜索”页面来显示过滤结果:

export async function load({ page, fetch }) {
        const term = page.query.term;
        const url = 'http://localhost:1337/posts';
        const data = await fetch(`${url}?categories.name_contains=${term}`);

        if (data.ok) {
            return { props: { posts: await data.json() } };
        }

        return {
            status: data.status,
            error: new Error(`Could not load ${url}`)
        };
    }

在同一页面(“搜索”)上,我导入了一个名为 PostList 的组件,该组件列出了帖子。我传递了组件的 props 帖子。

 <div class="post-card">
        {#each posts as post (post.id)}
            <PostList {post} />
        {/each}
 </div>

在 PostList 组件中,我尝试使用包含参数的 url 进行过滤。代码在{#each post.categories as category (category.id)}...

PostList 组件:

<script>
    // Script will be here
    export let post;
</script>

<!--HTML here-->
<div>
    <img src={post.image.formats.medium.url} alt={post.title} />
    <div class="mobile-display">
        <h3>
            <a href={post.slug}>
                {post.title}
            </a>
        </h3>
        <p class="fade-truncate">
            {post.description}
        </p>
        {#each post.categories as category (category.id)}
            <a href={`/search?term=${category.name}`}>
                {category.name}
            </a>
        {/each}
    </div>
</div>

我很确定问题出在加载函数中,它没有更新函数中的值 ${term}。

提前感谢您的帮助。

【问题讨论】:

    标签: javascript svelte sveltekit


    【解决方案1】:
    
    export async function load({ page, fetch }) {
            const term = page.query.get('term');
            const url = 'http://localhost:1337/posts';
            const data = await fetch(`${url}?categories.name_contains=${term}`);
    
            if (data.ok) {
                return { props: { posts: await data.json() } };
            }
    
            return {
                status: data.status,
                error: new Error(`Could not load ${url}`)
            };
        }
    

    这样试试

    【讨论】:

    • 非常感谢!我在文档中看到过类似的内容,但从未尝试在 get 方法中使用字符串作为参数。谢谢!你帮了我很多!
    猜你喜欢
    • 2022-08-05
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多