Svelte组件传递questionIndex时自动添加逗号问题排查
解决Svelte组件传递索引时自动添加逗号的问题
我有两个Svelte组件:Question.svelte和QuestionList.svelte。Question组件的清除按钮可清除自身单选按钮的选中状态;QuestionList组件的清除按钮可清除所有选中项。初始遍历打印对象格式正常,但从Question组件打印索引时,questionIndex显示为带逗号的字符串(如"1, ")而非纯数字,需要解决这个自动添加逗号的问题,传递纯数字索引。
问题原因
问题出在QuestionList.svelte的组件传参代码里,questionIndex属性的末尾多了一个逗号。这个逗号会被Svelte错误解析,导致传递给子组件的索引值变成带逗号的字符串,而非纯数字。
修复步骤
- 打开
QuestionList.svelte,找到{#each}循环里的Question组件调用代码 - 去掉
questionIndex = {Number(index)},后面的逗号,直接写成questionIndex={index}(index本身就是数字类型,无需额外转成Number)
修改后的完整代码
QuestionList.svelte
<script> import Question from './Question.svelte'; export let questions = [ { id: 1, text: '你最喜欢的颜色是什么?', options: ['红色', '蓝色', '绿色'], selectedOption: "" }, { id: 2, text: '你最喜欢的动物是什么?', options: ['猫', '狗', '鸟'], selectedOption: "" } ]; function handleOptionChange(questionIndex, selectedOption) { questions[questionIndex].selectedOption = selectedOption; } function clearAllSelections() { questions = questions.map((question) => ({...question, selectedOption: ""})); console.log('已清除所有选中项'); console.log(questions); } function clearSingleSelection(e) { console.log(e); const questionIndex = e.detail; console.log(`已清除单项: ${questionIndex}---`); console.log(questions); questions[questionIndex].selectedOption= ""; } console.log(`QuestionList.svelte`, questions); </script> {#each questions as question, index} <Question questionId={question.id} question={question.text} options={question.options} selectedOption={question.selectedOption} questionIndex={index} on:clearSingleSelection={clearSingleSelection} /> {/each} <button on:click={clearAllSelections}>清除所有</button>
Question.svelte
<script> import { createEventDispatcher } from 'svelte'; export let question, questionId, questionIndex; export let options = []; export let selectedOption = ''; const dispatch = createEventDispatcher(); // 处理选项变更 function handleChange(event) { const selectItem = { id: questionId, selectedOption: event.target.value, } console.log(`来自Question.svelte,已变更索引 ${questionIndex}--`); dispatch('optionChange', selectItem); } function handleSingleClear() { dispatch('clearSingleSelection', questionIndex); console.log(`来自Question.svelte,已清除索引 ${questionIndex}--`); } console.log(`Question.svelte中的问题索引: ${questionIndex}---`); </script> <div class="question-item"> <div class="question-section"> <p>{question}</p> </div> <div class="option-section"> {#each options as option} <input type="radio" name={questionId} value="{option}" checked={option === selectedOption} on:change={handleChange} /> <label for="{option}">{option}</label> {/each} </div> <button type="button" on:click={handleSingleClear}>清除</button> </div>
内容的提问来源于stack exchange,提问作者CrazyUser4232434
相关产品推荐
相关产品推荐

