输入值绑定在循环中不起作用



我正在尝试通过创建可重用的输入字段来压缩我的代码。因此,我声明了一个对象数组来循环并创建字段。乍一看,这工作正常。我的问题是变量视频搜索始终未定义。该函数被调用,但不使用我输入的值。有没有我没有看到绑定的方面?这是我的代码:

let values = {
song: "",
video: null,
tab: null
};
let videoSearch;
let tabSearch;
let videos;
const inputs = [
{
label: "Song",
value: values.song
},
{
label: "Search Youtube",
value: videoSearch,
func: debounce(searchYoutube, 300)
},
{
label: "Search Songsterr",
value: tabSearch,
func: debounce(searchYoutube, 300)
}
];
async function searchYoutube() {
console.log(videoSearch);
if (videoSearch && videoSearch.length > 3) {
// ... do ApiCall
}
}
{#each inputs as { value, label, func }}
<div class="input-container">
<input on:input={func} bind:value />
<label class={value ? 'flying-label' : ''}>{label}</label>
</div>
{/each}

编辑

我为它创建了一个 REPL。

您的问题是您正在用输入的值覆盖,删除对videoSearch的引用。您可以通过向videoSearch功能添加一些日志记录来轻松看到这一点:

async function searchYoutube() {
console.log(inputs[1]);
...
}

如果你想使用这个结构,我会在输入数组中引入一个getter/setter,而不是直接引用videoSearch字段,这将防止你的绑定被覆盖。

const inputs = [
{
label: "Search Youtube",
get value() { return videoSearch; },
set value(val) { videoSearch = val; },
func: searchYoutube
}
];

最新更新