Svelte中如何通过input标签更新writable store的值
问题原因与解决方法
你的错误主要来自语法错误、自定义Store未暴露set方法、反应式变量未正确声明,以及事件处理逻辑错误这几个点,下面分步给出修复方案:
1. Store 文件语法与逻辑修复
首先修复Store.js的语法错误,同时修正对象更新的响应式问题(直接修改原对象不会触发Svelte的响应式更新,需要返回新对象),如果要支持bind语法还需暴露set方法:
import { writable } from 'svelte/store'; function createSampleStore() { const sampleStore = writable({ property1a: 'value1a', property1b: 'value1b' }); // 补上缺失的闭合括号 return { subscribe: sampleStore.subscribe, updateValue: (propertyName, propertyValue) => sampleStore.update((o) => { // 返回新对象触发响应式更新,而非修改原对象 return { ...o, [propertyName]: propertyValue }; }), // 若要使用bind语法,必须暴露set方法 set: sampleStore.set }; } export const sampleStore = createSampleStore();
2. 组件代码修复
方案一:使用bind语法(简洁直观)
如果用bind:value,依赖Store暴露的set方法,此时无需手动处理输入事件,bind会自动同步值到Store:
<script> import { sampleStore } from './sampleStore.js'; // 反应式声明,确保Store内容变化时属性列表自动更新 $: propertyNames = Object.keys($sampleStore); </script> <ul> {#each propertyNames as propertyName} <li> {propertyName}: <input bind:value={$sampleStore[propertyName]} /> </li> {/each} </ul>
方案二:手动调用自定义updateValue方法(无需暴露set)
如果不想暴露set方法,就手动处理输入事件,调用自定义的更新方法:
<script> import { sampleStore } from './sampleStore.js'; $: propertyNames = Object.keys($sampleStore); function handleInput(event, propertyName) { sampleStore.updateValue(propertyName, event.target.value); } </script> <ul> {#each propertyNames as propertyName} <li> {propertyName}: <input value={$sampleStore[propertyName]} on:input={(e) => handleInput(e, propertyName)} /> </li> {/each} </ul>
关键错误说明
你遇到的sampleStore.set isn't a function错误,是因为bind:value={$sampleStore[propertyName]}在用户输入时,会自动调用Store的set方法更新值,但你最初的自定义Store只返回了subscribe和updateValue,没有暴露set方法,因此触发报错。另外原代码的on:input事件参数逻辑也有误,事件回调的参数是event而非value,且propertyValue是未定义变量。
内容的提问来源于stack exchange,提问作者joshCode25
相关产品推荐
相关产品推荐

