You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AlpineJS中基于x-init获取JSON的搜索栏失效问题排查

问题分析与修复方案

核心问题1:过滤逻辑错误

你的bands是对象数组(每个元素包含name属性),但filteredItems中的过滤逻辑用了i.startsWith(this.search)——这里的i是整个乐队对象,并非字符串,根本无法调用startsWith方法,导致过滤结果始终为空,自然渲染不出任何内容。

核心问题2:循环key值不规范

x-for的:key直接绑定了band对象,AlpineJS推荐使用唯一的原始值(如字符串、数字)作为key,避免潜在的渲染异常。


修复后的代码

<div x-data="{
        search: '', 
        bands: [], 
        get filteredItems() {
            return this.bands.filter(
                band => band.name.toLowerCase().startsWith(this.search.toLowerCase())
            )
        }
    }"  x-init="bands = await (await fetch('/bands/')).json()">
    <input x-model="search" placeholder="Search...">
 
        <template x-for="band in filteredItems" :key="band.name"> <!-- 若有唯一ID,优先用band.id -->
            <p x-text="band.name"></p>
        </template>

</div>

关键调整说明

  1. 把i.startsWith改为band.name.startsWith,明确访问对象的name属性进行匹配
  2. 新增toLowerCase()实现不区分大小写的搜索(可根据需求移除)
  3. 将:key改为band.name(若乐队名称唯一)或更可靠的唯一ID字段,保证循环渲染的稳定性

内容的提问来源于stack exchange,提问作者dirt1992

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:07:07