如何在Nuxt 2中管理输入框值的数组存储、更新与删除
解决textarea输入重复添加数组项的问题
方案一:分离维护多选项和自定义问题(推荐)
这种方式逻辑清晰,完全隔离多选框和输入框的操作,通过计算属性自动合并结果:
- 修改data定义,拆分原有数组为两个独立变量:
data() { return { checkboxSelected: [], // 专门存储多选框选中的项 customQuestion: '', // 存储textarea的实时输入值 } }
- 更新textarea绑定,用
v-model直接关联customQuestion,无需手动监听@input:
<div class="coffee-textarea"> <InputTextarea ref="questionTextarea" class="mt-4" placeholder="Sorularınız?" :required="true" v-model="customQuestion" /> </div>
- 添加计算属性生成最终数组,自动合并多选项和非空的自定义问题:
computed: { selectedQuestions() { const result = [...this.checkboxSelected] // 仅当输入框内容非空时,添加到结果数组 if (this.customQuestion.trim()) { result.push(this.customQuestion.trim()) } return result } }
- 调整多选框方法,操作新的
checkboxSelected数组:
methods: { selectCheckbox(text) { const index = this.checkboxSelected.indexOf(text) if (index !== -1) { this.checkboxSelected.splice(index, 1) } else { this.checkboxSelected.push(text) } } }
效果:
- 输入框内容变化时,只会更新
customQuestion,计算属性自动处理添加/移除逻辑 - 多选框操作仅影响
checkboxSelected,和输入框内容完全隔离 - 输入框为空时,自定义问题会自动从
selectedQuestions中消失
方案二:在原数组中标记区分项(最小改动)
如果不想调整数据结构,可通过特殊标识区分输入框内容,确保数组中仅保留一个输入框项:
- 修改
addQuestion方法,先移除旧的输入框项,再添加新内容(空值则不添加):
methods: { addQuestion(value) { const trimmedValue = value.trim() // 移除数组中已有的输入框项(用[自定义]前缀标记) const customIndex = this.selectedQuestions.findIndex(item => item.startsWith('[自定义]')) if (customIndex !== -1) { this.selectedQuestions.splice(customIndex, 1) } // 非空则添加带标记的内容 if (trimmedValue) { this.selectedQuestions.push(`[自定义]${trimmedValue}`) } }, // selectCheckbox方法保持原有逻辑不变 }
- 使用时处理标识:如果需要展示或提交数据,可去掉前缀:
// 示例:获取纯内容数组 const processedQuestions = this.selectedQuestions.map(item => { return item.startsWith('[自定义]') ? item.replace('[自定义]', '') : item })
内容的提问来源于stack exchange,提问作者Efe
相关产品推荐
相关产品推荐

