Svelte中radio触发on:change时无法获取最新bind:group绑定值
问题根因
Svelte中手动绑定的on:change回调执行顺序,早于bind:group对绑定变量的更新逻辑。tick()只会等待当前已入队的DOM更新任务完成,此时bind:group的变量更新还未入队,因此无论怎么等待,回调里拿到的都是更新前的旧值。
注意:原代码存在HTML规范问题:同组单选框的name属性必须保持一致,原代码每个单选框name都不同,会导致原生单选行为异常,下述修复代码已统一修正该问题。
修复方案
- 方案1(推荐):使用Svelte响应式声明监听绑定值变化
不需要额外绑定change事件,直接通过$:响应式语法监听变量,值更新后对应逻辑会自动触发,是最符合Svelte设计范式的写法:
<script> let tortilla = 'Plain'; // tortilla值更新时自动执行后续逻辑 $: console.log(tortilla) </script> <input name="tortilla" id="Plain" type="radio" bind:group={tortilla} value="Plain"> <label for="Plain">Plain</label> <input name="tortilla" id="Whole wheat" type="radio" bind:group={tortilla} value="Whole wheat"> <label for="Whole wheat">Whole wheat</label> <input name="tortilla" id="Spinach" type="radio" bind:group={tortilla} value="Spinach"> <label for="Spinach">Spinach</label>
- 方案2:直接从事件对象读取最新值
如果业务逻辑必须绑定在change回调中处理,无需调用tick()等待,直接从事件目标属性上获取当前选中的最新值即可:
<script> let tortilla = 'Plain'; function InputChange(e) { const currentValue = e.currentTarget.value; console.log(currentValue); } </script> <input on:change={InputChange} name="tortilla" id="Plain" type="radio" bind:group={tortilla} value="Plain"> <label for="Plain">Plain</label> <input on:change={InputChange} name="tortilla" id="Whole wheat" type="radio" bind:group={tortilla} value="Whole wheat"> <label for="Whole wheat">Whole wheat</label> <input on:change={InputChange} name="tortilla" id="Spinach" type="radio" bind:group={tortilla} value="Spinach"> <label for="Spinach">Spinach</label>
内容的提问来源于stack exchange,提问作者ofeenee
相关产品推荐
相关产品推荐

