繁体   English   中英

Sveltekit 如何设置基于查询参数选中的复选框?

[英]Sveltekit how do I set checkboxes checked based on query params?

我正在尝试使用 Sveltekit 根据查询参数将复选框设置为活动状态。 为此,我尝试使用 'url.searchParams.entries()' 方法获取所有路由查询参数,以从 URL 获取所有查询参数。

然后我试图遍历所有参数,然后遍历所有帖子并检查查询参数的值是否等于帖子中的值。 如果是这样,它应该将满足该值的每个复选框设置为 true。 然后在我的 HTML 中,我将选中的变量绑定到我的复选框。 但问题是,当我在查询参数中输入 4(或使用复选框的 select 4)时,它会检查所有复选框,但是,如果我输入 select 任何其他复选框,它不会做任何事情(除了从 JSON 占位符 api 查询数据)

这是我的 HTML:

<div class="grid grid-cols-2">         
   {#each posts as post}
      <div class="col-span-1">
         <input type="checkbox" bind:checked={checked} value={post.id} bind:group= 
           {selectedPosts} on:change="{() => updateValue(post.id)}" class="mr-2">
      </div>
      <div class="col-span-1">
         <label for="{post.id}">{post.id}</label>
      </div>
      {/each}
 </div>

这是在我的脚本标签内:

import { filter, results } from '../../stores.js';
    import { page } from '$app/stores';

    let checked = false
    let selectedPosts = []
    const posts = [
        { 
            name: 'post',
            id:'1' 
        }, 
        { 
            name: 'post',
            id: '2'
        }, 
        {
            name: 'post',
            id: '3'
        },
        {
            name: 'post',
            id: '4'
        }
    ]
    
    $:  {
        //If the query params would be '?posts=1', the output would be ['posts', '1']
        let params = [...$page.url.searchParams.entries()]
        
        params.forEach(param => {
            //Returns the first param. In this case '1'
            let value = param[1]

            posts.forEach(post => {
                if(post.id === value){
                    console.log('true')
                    checked = true
                } else {
                    checked = false
                    console.log('false')
                }
            })
        });
    }
        

    async function updateValue(value) {
        
        filter.set(value)
    }

在我的商店中,我像这样设置查询参数:

export const results = derived(filter, (value) => {
    if(!value) return {};
    const data = fetch(`https://jsonplaceholder.typicode.com/todos/${value}`).then(res => {
        return res.json()
    })

    return data
});


filter.subscribe(value => {
    if(!value) return 
    goto(`/activiteiten/filter?post=${value.toString()}`)
    return value
})

最后,我从 JSON 占位符 API 返回一些派生存储数据。

使用bind:group时不需要bind:checked={checked} 我认为这是你问题的根源。 您正在为每个项目设置相同的checked变量。

if(post.id === value){
  console.log('true')
  checked = true
} else {
  checked = false
  console.log('false')
}

当您稍后根据此变量进行检查时,会出现意外行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM